3

I have an app that needs move from screen 1 to screen two ....now when the user presses the back button..it should show a dialog box...if the user presses yes it has to exit...any help?the upper solutions don't work

Nirupam Sharma
  • 31
  • 1
  • 1
  • 2

1 Answers1

11

It seems like you can use WillPopScope. You also need to pass a callback function which will indicate what will happen on pressing the back button. In your case, you can add the code to show an AlertDialog which will ask for exit confirmation from the user.

You can simply wrap your Scaffold inside a WillPopScope.

Example:

Widget build(BuildContext context) {
  return WillPopScope(
    child: /*Your scaffold widget*/
    onWillPop: () {
      return showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text("Confirm Exit"),
            content: Text("Are you sure you want to exit?"),
            actions: <Widget>[
              FlatButton(
                child: Text("YES"),
                onPressed: () {
                  SystemNavigator.pop();
                },
              ),
              FlatButton(
                child: Text("NO"),
                onPressed: () {
                  Navigator.of(context).pop();
                },
            )
          ],
        );
      }
    );
    return Future.value(true);
  },
bytesizedwizard
  • 5,529
  • 3
  • 17
  • 39