Search code examples
flutterflutter-dialog

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.


Solution

  • 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()
            ),
          ),
        );
      }