Flutter 如何将FloatingActionButton嵌入BottomNavigationBar居中凹槽
实现中间带凹槽的嵌入式FAB导航栏
现有代码的问题根源
当前实现达不到预期效果的核心原因有两个:
- 普通的
BottomNavigationBar是纯平组件,本身没有为FAB预留中间凹槽的切口逻辑,哪怕FAB位置摆放正确,导航栏也不会在对应位置凹陷出容纳FAB的缺口 - 原本4个导航项平均分布在导航栏全宽度上,没有给中间的FAB预留专属空隙
具体改造步骤
- 替换导航栏组件:把原有的
BottomNavigationBar替换为**BottomAppBar**,这是Flutter官方专门适配FAB停靠凹槽的导航组件,内置了和FAB形状匹配的圆形切口逻辑,不需要手动绘制凹槽形状 - 调整导航项排布:因为要把正中间的位置留给FAB,需要把原来的4个导航项拆成左右两组,左侧放2个、右侧放2个,用固定宽度的占位组件把中间位置空出来,避免导航项被凹槽遮挡
- 匹配FAB停靠位置:根据使用的FAB尺寸选择对应的停靠位置:标准尺寸FAB用
FloatingActionButtonLocation.centerDocked,mini尺寸FAB用FloatingActionButtonLocation.miniCenterDocked,这个位置会自动让FAB和BottomAppBar的凹槽精准对齐 - 微调细节参数:通过
BottomAppBar的notchMargin参数调整凹槽和FAB之间的留白距离,默认8.0的边距和原生效果一致
改造后的参考代码
Scaffold( floatingActionButton: FloatingActionButton( child: const Icon(Icons.add), onPressed: () { // 新增按钮的点击逻辑 }, ), // 和BottomAppBar凹槽匹配的停靠位置 floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked, bottomNavigationBar: BottomAppBar( // 调整凹槽和FAB的间距 notchMargin: 8.0, // 内置的圆形凹槽形状 shape: const CircularNotchedRectangle(), height: 60, color: Colors.white, // 排布左右两侧的导航项,中间留空给FAB child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ _buildNavItem( icon: Icons.restaurant_menu, label: 'Recipes', onTap: () => _onItemTapped(0), ), _buildNavItem( icon: Icons.list, label: 'Plans', onTap: () => _onItemTapped(1), ), // 占位空间,宽度匹配FAB尺寸,把右侧导航项挤到凹槽旁 const SizedBox(width: 48), _buildNavItem( icon: Icons.shopping_cart, label: 'Groceries', onTap: () => _onItemTapped(2), ), _buildNavItem( icon: Icons.account_circle, label: 'Account', onTap: () => _onItemTapped(3), ), ], ), ), ) // 通用导航项组件,保留图标+文字的展示效果 Widget _buildNavItem({ required IconData icon, required String label, required VoidCallback onTap, }) { return InkWell( onTap: onTap, child: Column( mainAxisSize: MainAxisSize.min, children: [ Icon(icon), Text(label, style: const TextStyle(fontSize: 12)), ], ), ); }
适配调整提示
- 如果需要保留导航项选中态的高亮效果,只需要在
_buildNavItem组件里根据当前的_selectedIndex调整图标和文字的颜色即可,和原BottomNavigationBar的交互表现完全一致 - 如果不需要凹槽的凸起阴影效果,可以把
BottomAppBar的elevation参数调低,匹配项目的整体设计风格
内容的提问来源于stack exchange,提问作者Millenial2020
相关产品推荐
相关产品推荐

