Using Navigator.popUntil and route without fixed n

2019-02-18 17:58发布

问题:

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?

回答1:

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

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

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

Navigator.popUntil(context, ModalRoute.withName("Foo"))


标签: dart flutter