Flutter Navigation push Replacement is not working when not placed in the first activity
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.
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.