I have several Page.
1. Start Page
2. Page 2
3. Page 3
4. Main Menu
From 1 -> 2. and 2 -> 3. i use this for navigation :
Navigator.of(context).push(new MaterialPageRoute<MyPage>(
builder: (BuildContext context) {
return new MyPage();
},
));
and for 3 -> 4. I want to use this (Push Replacement, will not going back), but it doesnt work and act like normal Push:
Navigator
.of(context)
.pushReplacement(new MaterialPageRoute(builder: (BuildContext context) {
return new MainMenuPage();
}));
Confusing.
pushReplacement<T extends Object?, TO extends Object?> method Null safety. Replace the current route of the navigator that most tightly encloses the given context by pushing the given route and then disposing the previous route once the new route has finished animating in.
To solve this problem, we need to use a different context. In this situation, the easiest solution is to introduce a new widget as child of MaterialApp. And then use that widget's context to do the Navigator call. That's All.
Push the given route onto the navigator, and then remove all the previous routes until the predicate returns true. The predicate may be applied to the same route more than once if Route. willHandlePopInternally is true. To remove routes until a route with a certain name, use the RoutePredicate returned from ModalRoute.
I had the same problem going on, guess it was due to the fact that my screen #3 came from a dialog and i wasn't disposing of it before. So what I did was:
Navigator.of(context).popUntil((route) => route.isFirst);
then
Navigator.pushReplacement(context, MaterialPageRoute(builder: (BuildContext context) => NewPage()));
Well, pushReplacement()
isn't supposed to stop you from going back to any page. As comes from its name, it Replaces the new page that you are trying to open with the current page in the routes stack.
For example, when you are in the second page, use the pushReplacement()
method and open the third page, when you hit the back button you will go to the first page and skip the second page.
To make it more clear you can navigate to the forth page like this:
[ 1 --push()--> 2 --pushReplacement()--> 3 --pushReplacement()--> 4]
and when you hit the back button you will get to the first page.
Now if you want to control the backButton in android you can use the WillPopScope()
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With