要在彈出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
變量,以便在對話框打開或關閉時更改其狀態。