繁体   English   中英

如何在 Flutter/GoRouter 中为 ShellRoute 使用 context.go() 方法

[英]How to use context.go() method for ShellRoute in Flutter/GoRouter

我有一个登录页面,登录后主页基本上。 主页有BottomNavigationBar ,就像 Instagram 一样,很明显不是GoRoute ,而是ShellRoute 所以, ShellRoute有一个key ,但它没有path参数,因此我不能使用context go 或推送方法。

我以为ShellRoute有一条path ,但事实并非如此。

你可以按照这里的示例代码,在GoRouter设置之后,你不需要ShellRoute的路径。 登录后,您只需 context.go('YOUR BottomNavigationBar's FIRST PAGE')。 在示例代码中,只需使用 context.go('/a') 即可一切正常!

你应该

  • 为您的“GoRouter”提供“initialLocation”参数
  • 给你的“ShellRoute”提供“routes”参数

完成这些之后,您就会明白为什么不需要向 ShellRoute 添加“路径”参数。

final GoRouter router = GoRouter(
  navigatorKey: _rootNavigatorKey,
  initialLocation: '/home',
  routes: <RouteBase>[
    /// Application shell
    ShellRoute(
      navigatorKey: _shellNavigatorKey,
      builder: (BuildContext context, GoRouterState state, Widget child) {
        return ScaffoldWithNavBar(child: child);
      },
      routes: <RouteBase>[
        /// The first screen after login.
        GoRoute(
          path: '/home',
          builder: (BuildContext context, GoRouterState state) {
            return const HomeScreen();
          },
        ),
        /// Second screen on the navigation bar
        GoRoute(
          path: '/discover',
          builder: (BuildContext context, GoRouterState state) {
            return const DiscoverScreen();
          },
          ///Post Detail Screen inside of Discover Screen
          routes: <RouteBase>[
            GoRoute(
              path: 'post_detail',
              parentNavigatorKey: _rootNavigatorKey,
              builder: (BuildContext context, GoRouterState state) {
                return const PostDetailScreen();
              },
            ),
          ],
        ),
      ],
    ),
  ],
);

当用户点击底部导航栏项目之一时,您可以在 ScaffoldWithNavBar() 小部件中使用context.go('/discover')

ShellRouteGoRoute使用context.go()时要记住的事情

  1. 在每个GoRoute中指定parentNavigatorKey属性
  2. 使用context.go()替换页面,使用 context.push( context.push()将页面推入堆栈

代码结构遵循:


final _parentKey = GlobalKey<NavigatorState>();
final _shellKey = GlobalKey<NavigatorState>();

|_ GoRoute
  |_ parentNavigatorKey = _parentKey   👈 Specify key here
|_ ShellRoute
  |_ GoRoute                            // Needs Bottom Navigation                  
    |_ parentNavigatorKey = _shellKey   
  |_ GoRoute                            // Needs Bottom Navigation
    |_ parentNavigatorKey = _shellKey   
|_ GoRoute                              // Full Screen which doesn't need Bottom Navigation
  |_parentNavigatorKey = _parentKey

在此处参考使用ShellRouteGoRouter的底部 NavigationBar 的详细代码和说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM