Flutter中如何通过GoRouter在指定路由隐藏BottomNavigationBar
更简洁可靠的判断方式
相比直接匹配路由字符串,推荐以下两种更符合GoRouter设计逻辑的方法:
方法一:利用路由名称判断(推荐)
先给详情页路由配置命名:
GoRoute( name: 'a-details', path: 'details', builder: (context, state) => const DetailsScreen(), ),
然后在ScaffoldWithNavBar中通过路由名称判断:
@override Widget build(BuildContext context) { final routerState = GoRouterState.of(context); final isDetailsPage = routerState.matchedRouteName == 'a-details'; return Scaffold( body: AnimatedBranchContainer( currentIndex: navigationShell.currentIndex, children: children, ), // 仅非详情页显示底部导航栏 bottomNavigationBar: isDetailsPage ? null : 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), ), ); }
方法二:通过导航分支层级判断
如果不想给路由命名,可检查当前分支是否存在子路由:
@override Widget build(BuildContext context) { // 判断当前分支是否进入了子页面(详情页) final inChildRoute = navigationShell.currentChild?.canPop() ?? false; return Scaffold( body: AnimatedBranchContainer( currentIndex: navigationShell.currentIndex, children: children, ), bottomNavigationBar: inChildRoute ? null : 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), ), ); }
为什么不推荐字符串匹配?
直接用contains('details')的方式缺乏健壮性,若后续新增类似路径的路由(如b/details),会出现误判。而通过路由名称或层级判断,更贴合GoRouter的路由管理逻辑,也更易维护。
内容的提问来源于stack exchange,提问作者musako
相关产品推荐
相关产品推荐

