Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show confirm dialog before leave screen in Flutter

I want to show alert dialog before dispose or leave the screen or at the latest show warning SnackBar, How can I do that?

I know how to show dialog and SnackBar but I don't know where I do that or when I tried to do it in dispose of life hook but it makes an error. due to context is dispose of before showing the dialog.

like image 863
Mahmoud Niypoo Avatar asked Dec 01 '19 06:12

Mahmoud Niypoo


People also ask

How do you show simple dialog in Flutter?

Creating SimpleDialog In Flutter We can create a simpledialog in flutter by using its constructor. To display the simple dialog we have to use showDialog() method. We will return simpledialog as the child widget to showDialog, which displays the dialog.

How do you dismiss dialog automatically 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.

How do I stop alert dialog from closing the Flutter?

To make your AlertDialog widget not close when user taps on the screen space outside the alert box, set barrierDismissible property to false in showDialog() helper method.


1 Answers

You can use WillPopScope widget:

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        final value = await showDialog<bool>(
          context: context,
          builder: (context) {
            return AlertDialog(
              content: Text('Are you sure you want to exit?'),
              actions: <Widget>[
                FlatButton(
                  child: Text('No'),
                  onPressed: () {
                    Navigator.of(context).pop(false);
                  },
                ),
                FlatButton(
                  child: Text('Yes, exit'),
                  onPressed: () {
                    Navigator.of(context).pop(true);
                  },
                ),
              ],
            );
          }
        );

        return value == true;
      },
      child: Scaffold(
        appBar: AppBar(),
        body: SafeArea(
          child: Container()
        ),
      ),
    );
  }
like image 67
Igor Kharakhordin Avatar answered Sep 22 '22 23:09

Igor Kharakhordin