An application consist of many screens and includes many navigation. Sometimes a user wants to take custom action while pressing mobile device’s back button. In this tutorial we will discuss about

How to handle in flutter?

You can perform multiple action on back button click. For example:

1) You can open popup, when user click on back button.

2) You can move to a New Screen.

3) You can go back to previous screen.

You can handle back button events by using WillPopScope widget.

Widget build(BuildContext context) {
  return WillPopScope(
         onWillPop: _onBackPressed,
         child: Container(),
      );
}

Now create _onBackPressed method to handle your events.

Firstly, we try to open popup on back button click.

Future<bool> _onBackPressed() {
 return showDialog(
    context: context,
    builder: (context) => new AlertDialog(
    title: new Text('Exit App?'),
    content: new Text('Do you want to exit this App'),
    actions: <Widget>[
       new GestureDetector(
       onTap: () => Navigator.of(context).pop(false),
        child: Text("NO"),
   ),
    SizedBox(height: 16),
          new GestureDetector(
          onTap: () => Navigator.of(context).pop(true),
          child: Text("YES"),
      ),
    ],
   ),
) ??
false;
}

Second option move to another window

Future<bool> _onBackPressed() {
Navigator.of(context)
.pushReplacement(MaterialPageRoute(builder: (BuildContext context) => DashboardScreen()));
}

Third option is move back to previous screen.

Future _onBackPressed() {
Navigator.of(context).pop();
}