我有底部导航栏的 View ,当您按下导航栏项目时,新的路线将被推送到 View 中。

 final navigatorKey = GlobalKey<NavigatorState>();

 @override
  Widget build(BuildContext context) => MaterialApp(
    home: Scaffold(
      key: _scaffoldKey,
      body: _buildBody(context),
      bottomNavigationBar: _buildBottomNavigationBar(context),
    ),
  );

 void routeToView(routeIndex) {
      navigatorKey.currentState.pushNamed(pagesRouteFactories.keys.toList()[routeIndex]);
  }

我想防止在当前 View 上推送相同的路由。我想将当前路线与我们尝试插入的新路线进行比较,如果相同则忽略插入路线。

如果要尝试的路线与我相同,我想将 View 滚动到顶部

有任何想法吗。

最佳答案


https://stackoverflow.com/a/46498543/2554745
这是我能想到的最接近的解决方案:

Navigator.of(context).pushNamedAndRemoveUntil(
  "newRouteName",
  (route) => route.isCurrent && route.settings.name == "newRouteName"
      ? false
      : true);
如果路由名称是“newRouteName”,它将弹出当前路由,然后推送新的路由,否则将不会弹出任何内容。
编辑:最新的flutter提供ModalRoute.of(context).settings.name以获取当前路线的名称。

关于Flutter:如何避免在现有路线上推同一条路线,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54410461/

10-12 06:54