Go路由器:使用GoRoute和ShellRoute。

6

如何处理GoRoute和ShellRoute的路由是最佳方法。

我有3个屏幕。 设置 - 全屏显示 A - 显示底部导航(使用Shelled Route包装) B - 显示底部导航(使用Shelled Route包装)

在这种配置中,我遇到的唯一问题是当我进入设置屏幕时缺少返回按钮。我该如何解决?

final goRouter = GoRouter(
  initialLocation: '/a',
  navigatorKey: _rootNavigatorKey,
  routes: [
    GoRoute( // = Do not show Bottom Navigation, just a full screen
      path: '/settings',
      pageBuilder: (context, state) => const NoTransitionPage(
        child: SettingsPage(),
      ),
    ),
    ShellRoute( // ShellRoute = Show Bottom Navigation
      navigatorKey: _shellNavigatorKey,
      builder: (context, state, child) {
        return ScaffoldWithBottomNavigation(
          tabs: tabs,
          child: child,
        );
      },
      routes: [
        GoRoute( 
          path: '/a',
          pageBuilder: (context, state) => const NoTransitionPage(
            child: HomeScreen(label: 'A', detailsPath: '/a/details'),
          ),
          routes: [
            GoRoute(
              path: 'details',
              builder: (context, state) => const DetailsScreen(label: 'A'),
            ),
          ],
        ),
        GoRoute(
          path: '/b',
          pageBuilder: (context, state) => const NoTransitionPage(
            child: HomeScreen(label: 'B', detailsPath: '/b/details'),
          ),
          routes: [
            GoRoute(
              path: 'details',
              builder: (context, state) => const DetailsScreen(label: 'B'),
            ),
          ],
        ),
      ],
    ),
  ],
);
2个回答

11

代码中的错误

  1. 使用 context.go('/someRoute') 将页面推入堆栈
  2. 未使用 GoRoute 的 parentNavigatorKey 属性。

可能的解决方案:

  1. 使用 context.push('/someRoute') 将页面推入堆栈,然后才能在推入的页面中看到返回按钮。

  2. 在每个 route 中使用 parentNavigatorKey 属性,并明确指定当前 GoRoute 所在的位置。

    • 如果页面是 ShellRoute 的子级: parentNavigatorKey:_shellNavigatorKey
    • 如果页面是 MainRoute 的子级: parentNavigatorKey:_rootNavigatorKey

更新的设置路由:

GoRoute( 
      parentNavigatorKey:_rootNavigatorKey       Specify explicity that settings page lies in the Main Route 
      path: '/settings',
      pageBuilder: (context, state) => const NoTransitionPage(
        child: SettingsPage(),
      ),
    ),

现在您将摆脱位于ShellRoute内部的bottomNavigationBar


请参考使用ShellRouteGoRouter的底部NavigationBar的详细代码和解释这里


1
非常感谢您的回复。这解决了我所有的问题。 我已经将其应用到我的代码中,我已经实现了我想要的一切。谢谢! - Ensei Tankado

4

要添加返回按钮有两种方法:

  1. 使用push而不是go:

如果使用push,返回按钮将会带您回到之前的页面。

  1. 使用子路由,因此对于您的情况,设置页面需要成为另一个页面的子路由,但如果用户可以通过多个路径访问设置,则可能不可行。

所以我建议在导航到设置页面时使用push。


这是一个完美的答案。谢谢! - Ensei Tankado
1
然而,设置屏幕与底部导航栏一起出现。据我所知,这不应该发生,因为它已经不再是Shell Route的一部分。 - Ensei Tankado

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接