catch Android back button event on Flutter
In order to prevent navigating back WillPopScope is the correct way and should be used as follow:
class Page2 extends StatelessWidget { @override Widget build(BuildContext context) { return new WillPopScope( child: new Scaffold( appBar: new AppBar( title: new Text('Page 2'), ), body: new Center( child: new Text('PAGE 2'), ), ), onWillPop: () async { return false; }, ); }}Future<T> pushPage<T>(BuildContext context, Widget page) { return Navigator.of(context) .push<T>(MaterialPageRoute(builder: (context) => page));}
Can call the page like:
pushPage(context, Page2());
This is should be helpful.
@overrideWidget build(BuildContext context) { return WillPopScope( onWillPop: () { _moveToScreen2(context, ); }, child: Scaffold( key: _scaffoldKey, appBar: AppBar( leading: IconButton( icon: Icon(Icons.arrow_back), onPressed: () { _moveToScreen2(context); }), title: Text("Screen 1"), ), ), );}/*** This is probably too thin to be in its own method - consider using* `Navigator.pushReplacementNamed(context, "screen2")` directly*/void _moveToScreen2(BuildContext context) => Navigator.pushReplacementNamed(context, "screen2");
This code work for me.
I think there may be two reasons.
- Child of WillPopScope is Scaffold
No return in onWillPop
return new WillPopScope( onWillPop: () { if (!_isOpened) Navigator.pop(context); }, child: new Scaffold( key: SharedService.orderScaffoldKey, appBar: appBar, body: new Builder( builder: (BuildContext context) { return page; }, ), ),);