Flutter Navigation pop to index 1

FlutterDart

Flutter Problem Overview


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);
          },
        ),
      ),

Flutter Solutions


Solution 1 - Flutter

If you do not use named routes, you can use

Navigator.of(context).popUntil((route) => route.isFirst);

Solution 2 - Flutter

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 - Flutter

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 - Flutter

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 - Flutter

Use popUntil method as mentioned in the docs

> Typical usage is as follows: > > Navigator.popUntil(context, ModalRoute.withName('/login'));

Solution 6 - Flutter

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)

Solution 7 - Flutter

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

Solution 8 - Flutter

I tried other answers in this post, and somehow they causing the following exception.

To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by calling dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() method.

The relevant error-causing widget was
    MaterialApp 
lib/main.dart:72
When the exception was thrown, this was the stack
#0      Element._debugCheckStateIsActiveForAncestorLookup.<anonymous closure> 
package:flutter/…/widgets/framework.dart:3781
#1      Element._debugCheckStateIsActiveForAncestorLookup 
package:flutter/…/widgets/framework.dart:3795
#2      Element.dependOnInheritedWidgetOfExactType 
package:flutter/…/widgets/framework.dart:3837
#3      Theme.of 
package:flutter/…/material/theme.dart:128
#4      XXxxXX.build.<anonymous closure> 
package:xxx/widgets/xxx.dart:33
...
════════════════════════════════════════════════════════════════════════════════

The following answer fixed the issue. https://stackoverflow.com/a/52048127/2641128

Navigator.pushNamedAndRemoveUntil(context, '/', (_) => false);

Solution 9 - Flutter

//========================================================
          new ListTile(
            title: new RaisedButton(
              child: new Text("POP until"),
              onPressed: () {
                var route = new MaterialPageRoute(
                  builder: (BuildContext context) =>
                      new NextPage3(value:"hi there from 3"),
                );
               //Navigator.pop(context, ModalRoute.withName('/'));
                Navigator.popUntil(context,ModalRoute.withName('/'));                
              },
            ),
          ),
//========================================================

replace .pop with .popUntil, actually works very elegantly.

Solution 10 - Flutter

This always gets me the expected result. And will pop to route of current Navigator stack

 Navigator.of(context, rootNavigator: true).pop();

Solution 11 - Flutter

This will pop all the routes until the main default route and push to your destination route.

Navigator.pushNamedAndRemoveUntil(context, "destination_route", ModalRoute.withName('/')); 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIrishGringoView Question on Stackoverflow
Solution 1 - FlutterEdwin LiuView Answer on Stackoverflow
Solution 2 - Fluttermehrdad seyrafiView Answer on Stackoverflow
Solution 3 - FluttermilossView Answer on Stackoverflow
Solution 4 - Flutterdavid72View Answer on Stackoverflow
Solution 5 - FlutterShady AzizaView Answer on Stackoverflow
Solution 6 - FlutterMuhammad Tameem RafayView Answer on Stackoverflow
Solution 7 - FlutterAnshul KatariaView Answer on Stackoverflow
Solution 8 - Fluttere-j5View Answer on Stackoverflow
Solution 9 - FlutterIrishGringoView Answer on Stackoverflow
Solution 10 - FlutterTerblanche DanielView Answer on Stackoverflow
Solution 11 - FlutterDavid ArevaloView Answer on Stackoverflow