Flutter remove all routes

2020-05-14 05:05发布

I want to develop a logout button that will send me to the log in route and remove all other routes from the Navigator. The documentation doesn't seem to explain how to make a RoutePredicate or have any sort of removeAll function.

标签: dart flutter
6条回答
姐就是有狂的资本
2楼-- · 2020-05-14 05:14

i can done with the following code snippet :

 Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context) =>
    LoginScreen()), (Route<dynamic> route) => false),

if you want to remove all the route below the pushed route, RoutePredicate always return false, e.g (Route route) => false.

查看更多
混吃等死
3楼-- · 2020-05-14 05:20

I was able to accomplish this with the following code:

Navigator.of(context)
    .pushNamedAndRemoveUntil('/login', (Route<dynamic> route) => false);

The secret here is using a RoutePredicate that always returns false (Route<dynamic> route) => false. In this situation it removes all of the routes except for the new /login route I pushed.

查看更多
Explosion°爆炸
4楼-- · 2020-05-14 05:24

In case you want to go back to the particular screen and you don't use named router can use the next approach

Example:

Navigator.pushAndRemoveUntil(context,
                  MaterialPageRoute(builder: (BuildContext context) => SingleShowPage()),
                  (Route<dynamic> route) => route is HomePage
              );

With route is HomePage you check the name of your widget.

查看更多
▲ chillily
5楼-- · 2020-05-14 05:27

I dont know why no one mentioned the solution using SchedularBindingInstance,A little late to the party though,I think this would be the right way to do it originally answered here

    SchedulerBinding.instance.addPostFrameCallback((_) async {
                              Navigator.of(context).pushNamedAndRemoveUntil(
                                  '/login',
                                  (Route<dynamic> route) => false);
                            });

The above code removes all the routes and naviagtes to '/login' this also make sures that all the frames are rendered before navigating to new route by scheduling a callback

查看更多
ら.Afraid
6楼-- · 2020-05-14 05:33

Another solution is to use pushAndRemoveUnit(). To remove all other routes use ModalRoute.withName('/')

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

Reference: https://api.flutter.dev/flutter/widgets/NavigatorState/pushAndRemoveUntil.html

查看更多
干净又极端
7楼-- · 2020-05-14 05:36

Another alternative is popUntil()

Navigator.of(context).popUntil(ModalRoute.withName('/root'));

This will pop all routes off until you are back at the named route.

查看更多
登录 后发表回答