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

Flutter中如何通过GoRouter在指定路由隐藏BottomNavigationBar

解决方案:在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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 21:27:38