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

使用GoRouter的context.go()跳转时如何保留导航栈及路由配置疑问

GoRouter导航栈保留问题及ShellRoute场景处理

背景说明

  • 使用context.go()导航时,若目标路由是当前路由的子路由,会将其添加到现有路由上方,保留导航栈;若目标路由是非子路由(如/another-route),现有路由会被目标路由替换。
  • context.push()可实现跳转并保留导航栈,但Web端默认不会更改URL;虽可通过设置GoRouter.optionURLReflectsImperativeAPIs = true;让URL同步变化,但因context.push()是命令式API,不想使用。

现有路由配置

final _rootNavigation = GlobalKey<NavigatorState>(debugLabel: 'root');
final route = GoRouter(
  initialLocation: '/signup',
  navigatorKey: _rootNavigation,
  routes: [
    GoRoute(
      parentNavigatorKey: _rootNavigation,
      path: '/signup',
      builder: (context, state) => const SignUpScreen(),
    ),
    GoRoute(
      parentNavigatorKey: _rootNavigation,
      path: '/signin',
      builder: (context, state) => const SignInScreen(),
    ),
  ],
);

当前现象:从/signup通过context.go('/signin')跳转到/signin时,SignUpScreen会被SignInScreen替换。

核心疑问

是否是路由配置错误导致了该现象?正确的路由配置是否应为以下形式?

final route = GoRouter(
  initialLocation: '/auth',
  navigatorKey: _rootNavigation,
  routes: [
    GoRoute(
      parentNavigatorKey: _rootNavigation,
      path: '/auth',
      redirect: (_, __) => '/auth/signup',
      routes: [
        GoRoute(
          parentNavigatorKey: _rootNavigation,
          path: 'signup',
          builder: (context, state) => const SignUpScreen(),
        ),
        GoRoute(
          parentNavigatorKey: _rootNavigation,
          path: 'signin',
          builder: (context, state) => const SignInScreen(),
        ),
      ],
    ),
  ],
);

延伸场景问题

若上述配置正确,那么在使用BottomNavigationBar并配合ShellRoute或StatefulShellRoute时,跳转到非Shell子路由的场景下该如何处理?

注:问题与Flutter Web无关,仅因context.push()是命令式API而不想使用它。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 09:52:34