阅读量:0
要在弹出AlertDialog时禁止背景滚动,可以使用WillPopScope
和Navigator
来实现
import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: Text('AlertDialog 示例')), body: Home(), ), ); } } class Home extends StatefulWidget { @override _HomeState createState() => _HomeState(); } class _HomeState extends State<Home> { bool _isDialogOpen = false; void _showDialog() { setState(() { _isDialogOpen = true; }); showDialog( context: context, barrierDismissible: false, // 设置为false,以防止对话框在点击背景时消失 builder: (BuildContext context) { return AlertDialog( title: Text('提示'), content: Text('这是一个AlertDialog'), actions:<Widget>[ FlatButton( child: Text('确定'), onPressed: () { Navigator.of(context).pop(); setState(() { _isDialogOpen = false; }); }, ) ], ); }, ); } @override Widget build(BuildContext context) { return WillPopScope( onWillPop: () async { if (_isDialogOpen) { // 如果对话框打开,不允许返回 return false; } else { // 如果对话框关闭,允许返回 return true; } }, child: Stack( children: [ ListView.builder( itemCount: 30, itemBuilder: (BuildContext context, int index) { return ListTile(title: Text('Item $index')); }, ), Positioned( bottom: 16, right: 16, child: FloatingActionButton( onPressed: _showDialog, child: Icon(Icons.add), ), ), ], ), ); } }
在这个示例中,我们使用WillPopScope
来控制返回操作。当对话框打开时,我们不允许用户通过返回按钮关闭对话框。同时,我们使用setState
来更新_isDialogOpen
变量,以便在对话框打开或关闭时更改其状态。