Flutter:如何避免在现有路线上推同一条路线

skj*_*ini 5 flutter

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

 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]);
  }
Run Code Online (Sandbox Code Playgroud)

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

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

有任何想法吗。

Har*_*dia 13

NavigatorState doesn't expose an API for getting the path of the current route, and Route doesn't expose an API for determining a route's path either. Routes can be (and often are) anonymous. You can find out if a given Route is on the top of the navigator stack right now using the isCurrent method, but this isn't very convenient for your use case.

/sf/answers/3254898041/

This is the closest solution I could think of:

Navigator.of(context).pushNamedAndRemoveUntil(
  "newRouteName",
  (route) => route.isCurrent && route.settings.name == "newRouteName"
      ? false
      : true);
Run Code Online (Sandbox Code Playgroud)

It will pop the current route if name of the route is "newRouteName" and then push new one, else will not pop anything.

Edit: Latest flutter provides ModalRoute.of(context).settings.name to get the name of current route.

  • 每当您在变量中推送新路由时,存储 currentRouteName。并在推动之前进行比较。那将是你的解决方案。 (4认同)