PAYATHON 2026

GoRouter 中如何让 NavigationBar 选中项与当前路由保持同步

数据小陈

结论

NavigationBar 的 selectedIndex 不要只依赖组件内部的 currentPageIndex。在 GoRouter 场景下,当前路由才是判断选中项的依据:用当前 location(如 state.uri.path 或 GoRouterState.of(context).uri.path)计算选中索引,点击导航项时只负责调用 context.go(...) 切换路由。

为什么会出现这个问题

你的 NavigationBar 里,currentPageIndex 初始值是 0。点击 Search 或 Settings 时,setState 会改掉局部索引,同时 context.go 切换路由;但路由切换后,如果这个 NavigationAppBar 不是随路由重建的同一外壳,局部状态可能保留旧值,或者新页面重建时又回到 0。这样高亮状态和当前路由就不是同一个来源,容易不同步。用户通过返回、深链接进入 /search 时也会出现同样问题。

推荐方案:用 ShellRoute 包住导航栏

把 NavigationBar 放到 ShellRoute 的外壳里,由 state.uri.path 计算 selectedIndex,这样任何路由变化都会触发外壳 builder 重新执行。

final GoRouter router = GoRouter(
  initialLocation: '/',
  routes: <RouteBase>[
    ShellRoute(
      builder: (context, state, child) {
        return Scaffold(
          body: child,
          bottomNavigationBar: NavigationAppBar(
            currentPath: state.uri.path,
          ),
        );
      },
      routes: <RouteBase>[
        GoRoute(
          path: '/',
          builder: (context, state) => HomeScreen(),
        ),
        GoRoute(
          path: '/search',
          builder: (context, state) => SearchScreen(),
        ),
        GoRoute(
          path: '/setting',
          builder: (context, state) => SettingScreen(),
        ),
      ],
    ),
  ],
);

把 NavigationAppBar 改成无状态组件,只根据传入路径计算索引:

class NavigationAppBar extends StatelessWidget {
  const NavigationAppBar({
    super.key,
    required this.currentPath,
  });

  final String currentPath;

  int get currentPageIndex {
    switch (currentPath) {
      case '/search':
        return 1;
      case '/setting':
        return 2;
      case '/':
      default:
        return 0;
    }
  }

  @override
  Widget build(BuildContext context) {
    return NavigationBar(
      selectedIndex: currentPageIndex,
      indicatorColor: AppColors.primary,
      onDestinationSelected: (int index) {
        switch (index) {
          case 0:
            context.go('/');
            break;
          case 1:
            context.go('/search');
            break;
          case 2:
            context.go('/setting');
            break;
        }
      },
      destinations: const <NavigationDestination>[
        NavigationDestination(
          selectedIcon: Icon(Icons.home),
          icon: Icon(Icons.home_outlined),
          label: 'Home',
        ),
        NavigationDestination(
          icon: Icon(Icons.search),
          label: 'Search',
        ),
        NavigationDestination(
          icon: Icon(Icons.settings_outlined),
          label: 'Setting',
        ),
      ],
    );
  }
}

注意事项

  • 不要再在 onDestinationSelected 里用 setState 维护 currentPageIndex,否则局部状态和路由可能再次分叉。
  • 如果以后有 /search/detail 这类子路由,可以用 currentPath.startsWith('/search') 或按第一段路径映射索引,避免详情页高亮丢失。
  • ShellRoute 适合底部导航栏一直显示的页面结构。如果需要每个 tab 保留自己的导航栈,可以了解 StatefulShellRoute.indexedStack,但它的写法和普通 ShellRoute 不同,需要结合实际使用的 go_router 版本处理。
  • 如果 NavigationAppBar 不在 ShellRoute 里,也可以在它的 build 中通过 GoRouterState.of(context).uri.path 读取当前路径,但要确保该 widget 位于 GoRouter 的路由上下文之下。

备注:内容仅供参考。