Home » Android » android – Flutter Navigation push Replacement is not working when not placed in the first activity

android – Flutter Navigation push Replacement is not working when not placed in the first activity

Posted by: admin June 15, 2020 Leave a comment

Questions:

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.

How to&Answers:

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()));

Answer:

Now i’m using alternative way, Using pushReplacement instead of push for navigate and add WillPopScope for going back. So when i reach screen no 3. The replacement is work.

Answer:

i think that you don’t want to go with screen no 3 if the user is once reach screen no 4 then you can use Navigator.pop(context); before the transferring the control to screen no 4.

Answer:

Albeit your WillPopScope solution will work and is the appropriate solution for some navigation workflows, I am finding that the root of the problem is gaining better control over the Flutter Navigator, particular ensuring that the Back button and what should be on the Navigator stack, at any given User Action within an app is using Named Routes for all Navigations, this article is a great guide, to declaring Routes and then using named Routes with the Navigator to ensure that Navigator stack always contains the exact routes you want for any given navigation flow:

https://medium.com/flutter-community/flutter-push-pop-push-1bb718b13c31

Answer:

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.