You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go Router:如何在Widget内实现嵌套导航

Go Router 实现 Widget 内嵌套导航

当然可以,Go Router 完全支持在 Widget 内部实现你需要的嵌套导航效果,核心可以通过两种方式实现:

方式一:利用 ShellRoute 构建嵌套路由结构

适合全局框架下的局部嵌套场景(比如主布局侧边栏+内容区的独立导航栈),外层作为容器,内层路由拥有独立的导航历史:

final GoRouter _router = GoRouter(
  routes: [
    ShellRoute(
      builder: (context, state, child) {
        // 外层容器 Widget,示例为带侧边栏的布局
        return Scaffold(
          body: Row(
            children: [
              NavigationRail(
                destinations: const [
                  NavigationRailDestination(icon: Icon(Icons.home), label: Text('首页')),
                  NavigationRailDestination(icon: Icon(Icons.settings), label: Text('设置')),
                ],
                selectedIndex: _selectedIndex,
                onDestinationSelected: (index) {
                  setState(() => _selectedIndex = index);
                  context.go(index == 0 ? '/home' : '/settings');
                },
              ),
              // 嵌套导航的内容展示区
              Expanded(child: child),
            ],
          ),
        );
      },
      // 嵌套的子路由组,各自拥有独立导航栈
      routes: [
        GoRoute(
          path: '/home',
          builder: (context, state) => HomeScreen(),
          routes: [
            GoRoute(
              path: 'detail/:id',
              builder: (context, state) => HomeDetailScreen(id: state.pathParameters['id']!),
            ),
          ],
        ),
        GoRoute(
          path: '/settings',
          builder: (context, state) => SettingsScreen(),
          routes: [
            GoRoute(
              path: 'profile',
              builder: (context, state) => ProfileScreen(),
            ),
          ],
        ),
      ],
    ),
  ],
);

方式二:在子 Widget 中创建独立 GoRouter 实例

适合完全隔离的局部导航场景(比如弹窗、卡片内的独立导航流),局部区域使用独立的路由配置:

class NestedNavigationCard extends StatelessWidget {
  final GoRouter _nestedRouter = GoRouter(
    initialLocation: '/nested/main',
    routes: [
      GoRoute(
        path: '/nested/main',
        builder: (context, state) => NestedMainScreen(),
        routes: [
          GoRoute(
            path: 'subpage',
            builder: (context, state) => NestedSubScreen(),
          ),
        ],
      ),
    ],
  );

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: 300,
      height: 400,
      child: MaterialApp.router(
        routerConfig: _nestedRouter,
        debugShowCheckedModeBanner: false,
      ),
    );
  }
}

两种方式都能实现你需要的多导航栈独立切换效果,可根据实际布局的耦合需求选择对应方案。

内容的提问来源于stack exchange,提问作者mechanic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 14:12:05