【问题标题】:How to kill a navigation stack? Pop all previous screens in Flutter? [duplicate]如何杀死导航堆栈?在 Flutter 中弹出所有以前的屏幕? [复制]
【发布时间】:2019-04-16 13:23:49
【问题描述】:

所以我有这种将用户从一个屏幕推送到另一个屏幕的演练(总共六个屏幕)。在最后一页中,我希望用户按“完成”并将他带回第一个屏幕,而不能弹回之前的任何屏幕。

现在它会弹出最后一个屏幕,但不会弹出任何其他屏幕,因此它可以将我带回我的原始屏幕,并能够在最后一个屏幕之前弹出回屏幕(希望最后一句话对你有意义,因为弹出了最后一个屏幕,所以我回到了前一个屏幕)。

知道如何解决这个问题吗?

谢谢!

【问题讨论】:

标签: flutter


【解决方案1】:

你要找的方法是popUntil(),看看实现https://api.flutter.dev/flutter/widgets/Navigator/popUntil.html或者https://api.flutter.dev/flutter/widgets/NavigatorState/popUntil.html

你可能不得不做类似的事情

Navigator.of(context).popUntil(ModalRoute.withName('/my-target-screen'));

(看看https://api.flutter.dev/flutter/widgets/ModalRoute/withName.html

或使用一些自定义函数 (https://api.flutter.dev/flutter/widgets/RoutePredicate.html)。

【讨论】:

    【解决方案2】:

    要从导航堆栈中弹出多个屏幕,就像在您给定的场景中一样,我们可以使用Navigator.popUntil。它采用BuildContextRoutePredicate 作为参数。导航器调用pop,直到给定RoutePredicate 的返回值为真。

    这是一个非常基本的例子。它使用ModalRoute.withName 创建RoutePredicate

    import 'package:flutter/material.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          routes: {
            '/': (BuildContext context) => Home(),
            '/another': (BuildContext context) => Another()
          },
        );
      }
    }
    
    class Home extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text('Home'),
                RaisedButton(
                  child: Text('Take me to another screen!'),
                  onPressed: () => Navigator.pushNamed(context, '/another'),
                )
              ],
            ),
          ),
        );
      }
    }
    
    class Another extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                RaisedButton(
                  child: Text('Next screen.'),
                  onPressed: () => Navigator.pushNamed(context, '/another'),
                ),
                RaisedButton(
                  child: Text('Pop em all.'),
                  onPressed: () => Navigator.popUntil(
                        context,
                        ModalRoute.withName('/'),
                      ),
                ),
              ],
            ),
          ),
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-12
      • 1970-01-01
      • 1970-01-01
      • 2020-11-08
      • 1970-01-01
      • 2020-07-27
      • 2021-03-22
      相关资源
      最近更新 更多