点击按钮时将显示alertDialog,几秒钟后自动消失。在Flutter中如何做到这一点?
2eafrhcq1#
最小值例如:5秒后关闭alertDialog。
alertDialog
showDialog( context: context, builder: (context) { Future.delayed(Duration(seconds: 5), () { Navigator.of(context).pop(true); }); return AlertDialog( title: Text('Title'), ); });
uurv41yg2#
如果在触发Future之前关闭对话框,Future.delayed可能会导致一些问题。因此,如果您使用它,请注意showDialog不是可解除的barrierDismissible: false,并且AlertDialog没有解除它的按钮。否则,您可以使用计时器:
Future.delayed
barrierDismissible: false
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; });
ojsjcaue3#
您可能希望使用“SnackBar”来显示自动消失的通知。
final snackBar = SnackBar( content: Text('This is where you put the notice.'), duration: Duration(seconds: 2), ); Scaffold.of(context).showSnackBar(snackBar);
toe950274#
我建议使用FutureBuilder,这样当用户在超时之前关闭对话框时,这将被自动解除。
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), ); }, ); }, );
4条答案
按热度按时间2eafrhcq1#
最小值例如:
5秒后关闭
alertDialog
。uurv41yg2#
如果在触发Future之前关闭对话框,
Future.delayed
可能会导致一些问题。因此,如果您使用它,请注意showDialog不是可解除的barrierDismissible: false
,并且AlertDialog没有解除它的按钮。否则,您可以使用计时器:
ojsjcaue3#
您可能希望使用“SnackBar”来显示自动消失的通知。
toe950274#
我建议使用FutureBuilder,这样当用户在超时之前关闭对话框时,这将被自动解除。