Debug School

rakesh kumar
rakesh kumar

Posted on

How can I make alertDialog disappear automatically after few seconds in Flutter

** Solution:**
Future.delayed(Duration(seconds: 1), () {
Navigator.of(context).pop(true);
});

Image description

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'),
                        );
                      });
Enter fullscreen mode Exit fullscreen mode

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;
});
Enter fullscreen mode Exit fullscreen mode

You might want to use a 'SnackBar' to show notice that disappears automatically.

final snackBar = SnackBar(
  content: Text('This is where you put the notice.'),
  duration: Duration(seconds: 2),
);
Scaffold.of(context).showSnackBar(snackBar);
Enter fullscreen mode Exit fullscreen mode

Refrence1

Top comments (0)