Flutter! Handle back button in a flutter Application | Override back arrow button in App bar()

Atul Kumar
2 min readSep 25, 2019

--

Want to go back?

An application has many screens for product feature listing and includes different screens to navigates. so on the basis of the current action, a user wants to take another action when press back button. how to handle in flutter?

  1. We want to show a pop-up before the close app or close some connection that app using.
  2. That can be used to confirm that the user wants to discard their changes when the press back button or back navigation arrow.

How can catch the back pressed event in Flutter?

You can handle a back pressed event in the Flutter with help of WillPopScope widget. and you will find onWillPop method

@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: _onBackPressed,
child: new Scaffold(
appBar: new AppBar(
title: new Text(
"On Back pressed",
style: new TextStyle(color: Colors.white),
),
),
body: new Center(
child: new Text("Home Page"),
),
),
);
}

Implement _onBackPressed Method with alert dialog

Future<bool> _onBackPressed() {
return showDialog(
context: context,
builder: (context) => new AlertDialog(
title: new Text('Are you sure?'),
content: new Text('Do you want to exit an 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;
}

Override back arrow button in Appbar()

Screen Navigation:

first screen → second screen (Press second screen app bar back button) → Third screen

→ override the leading method in AppBar

new AppBar(
title: new Text(
"Second screen",
style: new TextStyle(color: Colors.white),
),
leading: new IconButton(
icon: new Icon(Icons.arrow_back),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => ThirdScreen()),
);
},
),
)

See y’all!

--

--