An alertDialog is to be shown when a button is tapped and disappear automatically after few seconds. How can I do that in Flutter?
To Dismiss Dialog user needs to make use of an inbuilt class like showDialog. The dialog route created by this method is pushed to the root navigator. If the application has multiple Navigator objects. It may be necessary to call Navigator.
You can do it using showGeneralDialog and put dismissible property to false , using this will ensure you that you are the only one who is handling pop up, like in your any action buttons in dialog.
You can access and use the value that comes from your dialog option like this: showDialog( context: context, builder: (context) => Dialog( val: vale, ), ). then((valueFromDialog){ // use the value as you wish print(valueFromDialog); });
A Minimal E.g:
It Closes the alertDialog
after 5 seconds.
showDialog( context: context, builder: (context) { Future.delayed(Duration(seconds: 5), () { Navigator.of(context).pop(true); }); return AlertDialog( title: Text('Title'), ); });
Future.delayed
can cause some problems if you dismiss the dialog before the Future is triggered. So, if you use it be careful that the showDialog is not dismissable barrierDismissible: false
and that the AlertDialog hasn't buttons that dismiss it.
Otherwise, you can use a Timer:
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; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With