【问题标题】:Flutter - how avoid pushing same route twice?Flutter - 如何避免两次推送相同的路线?
【发布时间】:2021-11-05 20:08:30
【问题描述】:

我的应用导航的这种结构:

CupertinoTabScaffold ->tabBuilder:TabPage-> tabBar: CupertinoTabBar

我的标签页:

return MaterialApp(
  navigatorKey: navKey,    
  home: child,
);

我在每个标签中都有单独的导航。通过单击底部选项卡,我回到开头。这是我的代码,现在可以使用:

 key.currentState!.pushNamedAndRemoveUntil('/', ModalRoute.withName('/'));

对于每个标签,我都有自己的导航键。我将它传递给每个 TabPage。

但如果页面位于根目录,我需要避免两次推送相同的路线。我试过这段代码,但它不起作用:

  key.currentState!.pushNamedAndRemoveUntil("/",
    (route) => route.isFirst && route.settings.name == "/" ? false : true);

如何避免两次推送同一条路线?

【问题讨论】:

    标签: flutter dart navigation


    【解决方案1】:
    Navigator.of(context).pushNamedAndRemoveUntil(
       "newRouteName",
       (route) => route.isCurrent && route.settings.name == "newRouteName"
      ? false
      : true);
    

    如果路由名称为“newRouteName”,则弹出当前路由,然后推送新路由,否则不会弹出任何内容。

    编辑:最新的flutter提供了ModalRoute.of(context).settings.name来获取当前路由的名字。

    【讨论】:

      【解决方案2】:

      如果路由名称是新的路由名称,这将弹出当前路由,然后推送新的,否则不会弹出任何路由。

      Navigator.of(context).pushNamedAndRemoveUntil(
        "new",
        (route) => route.isCurrent && ModalRoute.of(context).settings.name == "new"
            ? false
            : true);
      

      【讨论】:

      • 这与我的版本有何不同?
      【解决方案3】:

      如果您使用的是BottomNavigationBar,您只需在onTap() 上添加一个检查器,以查看您是否要在同一页面上导航。要跟踪当前页面,您可以使用枚举或 int 等简单变量。 CupertinoTabBar 也有一个可用的 onTap 属性,类似于 BottomNavigationBar。

      BottomNavigationBar(
        items: <BottomNavigationBarItem>[...],
        currentIndex: _currentPage,
        onTap: (value){
          // Only navigate if a different page was clicked
          if(value != _currentPage){
            _currentPage = value;
            setState(() {
              switch(value) {
                // Page 0
                case 0:
                  key.currentState!.pushReplacementNamed(...);
                  break;
                // Page 1
                case 1:
                  key.currentState!.pushReplacementNamed(...);
                  break;
                
                ...
              }
            });
          }
        }
      )
      

      或者,如果您将 TabBar 与 TabBarView 一起使用,则显示的页面可以由控制器管理,如 guide 所示。

      【讨论】:

        猜你喜欢
        • 2019-06-21
        • 2013-04-28
        • 1970-01-01
        • 2017-08-16
        • 2012-12-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多