当用户点击按钮后,需要显示一个 alertDialog,并在几秒钟后自动消失。在 Flutter 中,我该如何实现这个功能?
一个最小的示例:
它会在5秒后关闭alertDialog
对话框。
showDialog(
context: context,
builder: (context) {
Future.delayed(Duration(seconds: 5), () {
Navigator.of(context).pop(true);
});
return AlertDialog(
title: Text('Title'),
);
});
Future.delayed
方法可能会导致问题,如果在 Future 触发之前关闭了对话框。所以,如果要使用它,请确保 showDialog
不可取消 barrierDismissible: false
,并且 AlertDialog 没有按钮可以关闭它。Timer timer = Timer(Duration(milliseconds: 3000), (){
Navigator.of(context, rootNavigator: true).pop();
});
showDialog(
... Dialog Code ...
).then((value){
// dispose the timer in case something else has triggered the dismiss.
timer?.cancel();
timer = null;
});
final snackBar = SnackBar(
content: Text('This is where you put the notice.'),
duration: Duration(seconds: 2),
);
Scaffold.of(context).showSnackBar(snackBar);
showDialog(
context: context,
builder: (context) {
return FutureBuilder(
future: Future.delayed(dismissDuration).then((value) => true),
builder: (context, snapshot) {
if (snapshot.hasData) {
Navigator.of(context).pop();
}
return AlertDialog(
content: Text(text),
);
},
);
},
);
Future<T>.delayed
构造函数。 - pskink