What is the difference between Navigator.pushReplacement and Navigator.pushAndRemoveUntil in flutter?


In flutter, we have two ways of exiting a page while destroying the current page. The first one is pushReplacement-

Navigator.pushReplacement(context, MaterialPageRoute(builder: (context){
      return LocationScreen();

The second one is pushAndRemoveUntil-

        context, MaterialPageRoute(builder: (context) => LocationScreen()), (
        route) => false);

These both appear to be exactly same. I searched through google, but couldn’t find a satisfactory answer. Can someone explain me the difference between these two?


Imagine your current navigation stack being something like this:


Now, you want to get to route /D. After calling pushReplacement, the navigation stack will look like this:


That’s it, there is nothing more you could do with this method. However, while using pushAndRemoveUntil, you could also specify the route predicate that will tell you when you need to stop popping your stack before pushing your next route. For instance, your route predicate is route /A, the result will look like this:


Notice, that routes /B and /C were removed from the stack.

To sum up: pushReplacement only replaces the top route while the pushAndRemoveUntil could replace multiple routes up until your defined predicate.

Answered By – mkobuolys

Answer Checked By – Terry (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *