Reputation: 795
My problem is that I have a main page then sign in page then a homepage where if I press logout in the homepage it should navigate me back to the main page which contains the willpopscope , what I'm trying to do is to prevent the user from pressing the back button in the main page so that the app does not return to the homepage without the user being signed in , the problem is that the willpopscope does not work when I Navigator.push the homepage , so whenever I press the back button it returns me to the home page.
I tried changing the position of WillPopScope, If I wrap the whole widget by it , it will never work for me
Code to reproduce
//Main page:
class MainActivity extends StatefulWidget {
final bool isWelcome;
MainActivity(this.isWelcome);
@override
State<StatefulWidget> createState() {
return OperateMainActivity(isWelcome);
}
}
class OperateMainActivity extends State<MainActivity> {
bool isWelcome = false;
OperateMainActivity(this.isWelcome);
@override
Widget build(BuildContext context) {
//print(isWelcome);
return MaterialApp(
home: MyHome(
isWelcome: isWelcome,
));
}
}
class myHome extends StatelessWidget
return Scaffold(
body: Center(
child: WillPopScope(
onWillPop: () async => false,
child: Container(....)
// Home page
Navigator.push(context,MaterialPageRoute(builder: (context) => MainActivity(false)));
//When pushing to main activity WillPopScope does not work
Upvotes: 1
Views: 5118
Reputation: 2675
WillPopScope
doesn't get called when you push. That's the logical behavior, because when you're pushing another view it goes above the current view in the stack. Therefore, the current view never pops out.
If you know that your MainActivity
is below you're current page in the stack, you could change:
Navigator.push(context,MaterialPageRoute(builder: (context) => MainActivity(false)));
to:
Navigator.pop(context); // This will make a call to onWillPop.
UPDATE:
For what you want to achieve, you could just use pushAndRemoveUntil
:
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(
builder: (context) {
return MainActivity();
},
),
(Route<dynamic> route) => false,
);
It will push the desired page and remove everything else from the stack.
Upvotes: 1