【问题标题】:Is there a way to limit the number of pages the Navigation Stack can maintain in a Flutter App?有没有办法限制导航堆栈在 Flutter App 中可以维护的页面数量?
【发布时间】:2019-04-06 16:14:19
【问题描述】:

在我的 Flutter 应用程序中,我注意到我的 Navigation Stack 不断增长。有没有办法限制导航堆栈中内存中的页数(比如最多 4 页)?

在用户触发一定数量的“返回”按钮后,是否可以最小化/关闭 Flutter 应用程序?

【问题讨论】:

    标签: dart flutter


    【解决方案1】:

    我不知道有任何设置可以让您进行设置。因此,我将提出一种自己处理的方法。

    以下两个变量是顶级,也就是说,您可以将它们放在类之外的任何位置。或者,您可以使用InheritedWidget 来存储数据,但为了简单起见,我不会这样做。

    int openedRoutes = 1, routePops = 0;
    

    有两种方法可以捕获路径弹出。您要么只能捕获来自系统的那些,例如Android 后退按钮,也可以接听您的 Navigator 流行电话。您要录制的所有手动操作都必须使用Navigator.maybePop 而不是Navigator.pop

    现在,您只需将所有页面包装在以下小部件中,该小部件使用WillPopScope 来跟踪routePops

    class TrackPops extends StatelessWidget {
      final Widget child;
    
      TrackPops({Key key, @required this.child}) : super(key: key);
    
      @override
      Widget build(BuildContext context) => 
          WillPopScope(child: child, onWillPop: () async {
                if (routePops++ >= backButtonLimit) /// [backButtonLimit] defined below
                  SystemChannels.platform.invokeMethod('SystemNavigator.pop');
                openedRoutes--;
                return true;
              });
    }
    

    现在,您可以在每次推送路由时只使用这两个变量。如前所述,InheritedWidget 将是惯用的路径,您只需使用 BuildContext.inheritFromWidgetOfExactType 检索即可。

    路径限制为4 且后退按钮按下为2 的示例实现:

    const int routeLimit = 4, backButtonLimit = 2;
    
    void pushRoute(BuildContext context, Route route) {
      if (openedRoutes >= routeLimit) return;
      Navigator.of(context).push(route);
      openedRoutes++;
      routePops = 0;
    }
    

    【讨论】:

    • 是的,这是一个很好的方法。但是如果颤振有一个方法来处理这个会很好。
    猜你喜欢
    • 2021-05-13
    • 1970-01-01
    • 2016-01-14
    • 2021-04-18
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 2015-03-23
    • 2018-06-23
    相关资源
    最近更新 更多