Is there any way I can catch the onBackPressed
event from Android back button?
I've tried the WillPopScope
but my onWillPop
function only triggered when I tap on the Material back arrow button
I put it like this:
class MyView extends StatelessWidget{
Widget build(BuildContext context) {
return new WillPopScope(
onWillPop: () async {
debugPrint("Will pop");
return true;
},
child: ScopedModel<AppModel>(
model: new AppModel(),
child: new Scaffold(......
I need to catch it because somehow my screen behaved incorrectly when it came to back button pressed, it pops the screen and the screen below it, but somehow, using material back arrow button works normal.
Update:
The code works, my problem was not in the pop of this screen, but on the previous screen, I use 2 MaterialApp widgets, and somehow it gave a weird behavior.
In order to prevent navigating back WillPopScope is the correct way and should be used as follow:
class Page2Route extends MaterialPageRoute {
Page2Route() : super(builder: (context) => new Page2());
}
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: () {
return new Future(() => false);
},
);
}
}
Can call the page like:
Navigator.of(context).push(new Page2Route());
Don't use below approach for navigation, as it has some issues with the latest Flutter:
Navigator.push(context, new Page2Route());
This is how I implemented mine and it works fine for me. You can try it out.
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () {
_moveToSignInScreen(context);
},
child: Scaffold(
key: _scaffoldKey,
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back),
onPressed: () {
_moveToSignInScreen(context);
}),
title: Text("Profile"),
),
),
);
}
void _moveToSignInScreen(BuildContext context) =>
Navigator.pushReplacementNamed(context, Routes.keySignIn);
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;
},
),
),
);