Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter remove all routes

Tags:

flutter

dart

People also ask

How do you delete all routes in flutter?

To remove all the routes below the pushed route, use a RoutePredicate that always returns false (e.g. (Route<dynamic> route) => false ). The removed routes are removed without being completed, so this method does not take a return value argument. The newly pushed route and its preceding route are notified for Route.

What is ModalRoute in flutter?

A route that blocks interaction with previous routes. ModalRoutes cover the entire Navigator. They are not necessarily opaque, however; for example, a pop-up menu uses a ModalRoute but only shows the menu in a small box overlapping the previous route. The T type argument is the return value of the route.


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.


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.


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.


Another solution is to use pushAndRemoveUntil(). 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


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.