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.
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;
});
Use popUntil method as mentioned in the docs
Typical usage is as follows:
Navigator.popUntil(context, ModalRoute.withName('/login'));
You can also do it like this
Navigator.of(context)
.pushNamedAndRemoveUntil('/Destination', ModalRoute.withName('/poptillhere'),arguments: if you have any);
The use case is to go the desired screen and pop the screens in between as you require.
For more info, you can check this Post Explaining other Solutions
Here Dashboard() is the screen name. So this will pop out all the screens and goto Dashboard() screen.
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(builder: (c) => Dashboard()),
(route) => false)
If you do not use named routes, you can use
Navigator.of(context).popUntil((route) => route.isFirst);
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.