Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Navigator.popUntil and route without fixed name

Tags:

flutter

dart

Is it possible to use Navigator.popUntil with routes that do not have fixed names?

I have a route created the following way:

  final _key_homepage = new GlobalKey<HomePageState>();

    Navigator.pushReplacement(context, new MaterialPageRoute(
      builder: (BuildContext context) =>  new HomePage(key: _key_homepage, somevariable1: 'some value', somevariable2: 'some value 2'),
    ));

Now when I receive push notification on any screen and display popup message, one of the buttons should lead to the route listed above. The route was already created and must be 'poped' to. How to do it?

With named route, it can be done like this:

 new FlatButton(
    child: new Text('Go to homepage'),
    onPressed: () {
      Navigator.popUntil(context, ModalRoute.withName('/homepage'));  

     //how to do the same without ModalRoute.withName('/homepage')

    },
)

Both 'key' and context of desired route is available. However recreating the route again does not feel like a good solution, because original route creation includes some variables (somevariable1, somevariable2, etc).

Any way to achieve this?

like image 338
Andrew Avatar asked Jul 26 '18 09:07

Andrew


People also ask

Can Flutter routes be named?

The solution is to define a named route, and use the named route for navigation. To work with named routes, use the Navigator.


1 Answers

You should add a setting when pushing your route; with a custom name

Navigator.pushReplacement(
  context,
  MaterialPageRoute(
    settings: RouteSettings(name: "Foo"),
    builder: ...,
  ),
);

Then you can use popUntil as you'd do with named routes

Navigator.popUntil(context, ModalRoute.withName("Foo"))
like image 125
Rémi Rousselet Avatar answered Oct 18 '22 21:10

Rémi Rousselet