Flutter Navigation pop to index 1
I am recursively adding routes to the navigator. There could be 20 views or more. Pop works as advertised, but I would like to pop to index 1 and remove all push history. is there a way to replace this pop command with something like... returntoIndex0...
new ListTile(
title: new RaisedButton(
child: new Text("POP"),
onPressed: () {
var route = new MaterialPageRoute(
builder: (BuildContext context) =>
new NextPage3(value:"hi there from 3"),
);
Navigator.pop(context);
},
),
),
Solution 1:
If you do not use named routes, you can use
Navigator.of(context).popUntil((route) => route.isFirst);
Solution 2:
In case you know exactly how many pops should be performed:
For example for 2 pops:
count = 0;
Navigator.popUntil(context, (route) {
return count++ == 2;
});
Solution 3:
If you are using MaterialPageRoute
to create routes, you can use this command:
Navigator.popUntil(context, ModalRoute.withName(Navigator.defaultRouteName))
Navigator.defaultRouteName
reflects the route that the application was started with. Here is the piece of code that illustrates it in more detail:
child: InkWell(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Image(
image: AssetImage('assets/img/ic_reset.png'),),
Text('Change my surgery details',
style: TextStyle(color: Colors.blue, decoration: TextDecoration.underline),),
],
),
onTap: () =>
Navigator.popUntil(context, ModalRoute.withName(Navigator.defaultRouteName))
),
Hope this helps.
Solution 4:
For me I used this when pushing a new page:
widget = MyWidget();
Route route = CupertinoPageRoute(builder: (context) => widget, settings:RouteSettings(name: widget.toStringShort()));
Navigator.push(context, route);
Then to go back to specific page:
Navigator.of(context).popUntil((route) => route.settings.name == "MyWidget");
Solution 5:
Use popUntil
method as mentioned in the docs
Typical usage is as follows:
Navigator.popUntil(context, ModalRoute.withName('/login'));