How to reset the base route in my Flutter App - that is pop any routes and replace it with a new one using Navigator

sjmcdowall picture sjmcdowall · Aug 28, 2018 · Viewed 12.1k times · Source

New to Flutter to please forgive me if this is obvious, but I have read the documentation and tried a bunch of the Navigator options but none of them work as I would like. The problem set: We have a complex (well, semi-complex) series of screens, etc. that handle the login / authorization / registration process. This can get down to 3 or 4 levels on the Route stack. This is all fine -- no worries.

The problem comes when we get a successful login event (from a few different paths) and want to go to the "home" page. Once we are on the home page that should be the new "root" of the Route tree (I am sure this isn't the correct terminology -- but I think the idea is solid).

So, given we could be 1/2/3 or even 4 levels down and want to "pop" and replace the whole stack (with any transition events, please) to a new top level root -- what magical Navigator set or methods will do this cleanly?

My current (horrid) approach is to hand "pop()" the levels and do a Navigator.pushReplacementNamed() call (they are all named routes here) but that isn't a generic solution (have to know exactly how many levels) and worse, it causes a "animation" transition to "pop" on the screen for a split second for each pop() which looks .. not very good.

TIA!

Answer

Rémi Rousselet picture Rémi Rousselet · Aug 28, 2018

Navigator expose more than just pop. You can do things such as the following:

Navigator.pushNamedAndRemoveUntil(context, '/', (_) => false);

This will basically push a home and remove all the routes behind the new one