Flutter Navigation pop to index 1

前端 未结 9 1305
梦毁少年i
梦毁少年i 2020-12-02 13:54

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.

相关标签:
9条回答
  • 2020-12-02 14:54

    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);
    
    0 讨论(0)
  • 2020-12-02 14:59

    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");
    
    0 讨论(0)
  • 2020-12-02 14:59
    //========================================================
              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.

    0 讨论(0)
提交回复
热议问题