Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 676
sjmcdowall Avatar asked Aug 27 '18 23:08

sjmcdowall


3 Answers

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

like image 200
Rémi Rousselet Avatar answered Oct 23 '22 02:10

Rémi Rousselet


Try this code:

    Navigator.pushAndRemoveUntil(
                    context,
                    MaterialPageRoute(
                      builder: (BuildContext context) => YourInitialPage(),
                    ),
                    ModalRoute.withName('/'));

If you don't want transition you can override or extend the MaterialPageRoute class

like image 4
diegoveloper Avatar answered Oct 23 '22 00:10

diegoveloper


The good news is now we can use pushReplacementNamed

Navigator.pushReplacementNamed(context, '/');

(Channel master, v1.15.4-pre.97, I'm not sure the previous version can do that)

like image 2
Tiến Trương Văn Avatar answered Oct 23 '22 01:10

Tiến Trương Văn