如何在Flutter中使用GoRouter隐藏特定路由中的BottomNavigationBar?

BoK*_*enU 4 flutter flutter-go-router

https://github.com/flutter/packages/blob/main/packages/go_router/example/lib/others/custom_stateful_shell_route.dart 在此代码中,即使显示详细信息,ButtomBar 也始终显示。但是,我想在查看“a/details”时隐藏ButtomBar。有没有办法做到这一点?

一种可能的方法是使用navigationShell.shellRouteContext.routerState.matchedLocation.contains('details'). 但我认为应该有一个更简单的方法。这应该怎么做呢?

具体来说,我想根据下一节中当前显示的页面来确定是否启用或禁用按钮栏。

class ScaffoldWithNavBar extends StatelessWidget {
  const ScaffoldWithNavBar({
    required this.navigationShell,
    required this.children,
    Key? key,
  }) : super(key: key ?? const ValueKey<String>('ScaffoldWithNavBar'));

  final StatefulNavigationShell navigationShell;

  /// ([AnimatedBranchContainer]).
  final List<Widget> children;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: AnimatedBranchContainer(
        currentIndex: navigationShell.currentIndex,
        children: children,
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Section A'),
          BottomNavigationBarItem(icon: Icon(Icons.work), label: 'Section B'),
        ],
        currentIndex: navigationShell.currentIndex,
        onTap: (int index) => _onTap(context, index),
      ),
    );
  }
Run Code Online (Sandbox Code Playgroud)

Adi*_*ora 11

要隐藏某些屏幕上的底部导航栏,您可以在您提供的示例中进行以下更改:https: //github.com/flutter/packages/blob/main/packages/go_router/example/lib/others/custom_stateful_shell_route。镖

首先创建两个GlobalKey:

final GlobalKey<NavigatorState> _rootNavigatorKey =
GlobalKey<NavigatorState>(debugLabel: 'root');
final GlobalKey<NavigatorState> _tabANavigatorKey =
GlobalKey<NavigatorState>(debugLabel: 'tabANav');
Run Code Online (Sandbox Code Playgroud)

在您创建的 GoRouter 中,将 _rootNavigatorKey 分配给 navigatorKey 参数,例如:

final GoRouter _router = GoRouter(
    navigatorKey: _rootNavigatorKey,
    initialLocation: '/a',
    routes: <RouteBase>[
       ...
    ]
)
Run Code Online (Sandbox Code Playgroud)

以及您想要隐藏底部导航栏的 shellRoutes,例如DetailsS​​creen,将 _rootNavigatorKey 添加到parentNavigatorKey,例如:

                  GoRoute(
                    path: 'details',
                    parentNavigatorKey: _rootNavigatorKey,
                    builder: (BuildContext context, GoRouterState state) =>
                    const DetailsScreen(label: 'A'),
                  ),
Run Code Online (Sandbox Code Playgroud)

现在,当您进入或推送到详细信息屏幕时,底部导航栏将不会显示。

GoRouter.of(context).go('/a/details');
Run Code Online (Sandbox Code Playgroud)

如果您还有更多问题,可以问我,我很乐意为您解答。