16

I want the same onBackPressed logic of Android in flutter application and I want to close the app when I click on phone back button.

Can any one tell me how to do this when we click on phone back not app back button.

android:

@Override
public void onBackPressed()
{
     // code here to show dialog
     super.onBackPressed();  // optional depending on your needs
}
ppreetikaa
  • 1,149
  • 2
  • 15
  • 22
kartheeki j
  • 2,206
  • 5
  • 27
  • 51

3 Answers3

29

You can use WillPopScope for that. It's a class that notifies you when the enclosing ModalRoute (internally used with the Navigator) is about to be popped. It even leaves you a choice to whether or not you want the pop to happen.

Just wrap the second screen's Scaffold in a WillPopScope.

return WillPopScope(
  onWillPop: () async {
    // You can do some work here.
    // Returning true allows the pop to happen, returning false prevents it.
    return true;
  },
  child: ... // Your Scaffold goes here.
);
Marcel
  • 8,831
  • 4
  • 39
  • 50
  • 2
    Drawback of this solution is that back gesture on iOS then is no longer working. – Timo Bähr Aug 09 '20 at 15:19
  • in android device getting a black screen with WillPopScope tried all solutions with a navigator in flutter – s.j Dec 22 '20 at 10:12
5

Hope this will help...

Future<bool> _onBackPressed() async {
    // Your back press code here...
    CommonUtils.showToast(context, "Back presses");
}

WillPopScope creates a widget that registers a callback to veto attempts by the user to dismiss the enclosing ModalRoute.

@override 
Widget build(BuildContext context) {
    return new WillPopScope(
        onWillPop: _onBackPressed,
        child: ...child
    );
}
Ankit
  • 135
  • 1
  • 8
0

You can use Navigator.pop(context); or Navigator.maybePop(context);;

And maybePop can be listened by WillPopScope#onWillPop

linkaipeng
  • 483
  • 7
  • 9