Flutter中BottomNavBar搭配FAB按钮布局异常问题求助
原始效果

原始代码:
bottomNavigationBar: BottomNavigationBar( type: BottomNavigationBarType.fixed, currentIndex: 0, backgroundColor: Color(0xFF0066EE), selectedItemColor: Colors.white, unselectedItemColor: Colors.white, items: const [ BottomNavigationBarItem(label: 'Home', icon: Icon(Icons.home)), BottomNavigationBarItem(label: 'Diary', icon: Icon(Icons.book)), BottomNavigationBarItem( label: 'Plans', icon: Icon(Icons.spoke_rounded)), BottomNavigationBarItem(label: 'More', icon: Icon(Icons.more)), ], onTap: (index) { if (index == 1) { Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) { final foodItemsModel = Provider.of<FoodItemsModel>(context, listen: false); return MealPlanPage(mealList: foodItemsModel.foodItems); }, ), ); } else if (index == 2) { Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) { return PlanPage(); }, ), ); } }, ),
期望效果

两次尝试的问题分析
第一次尝试:用BottomAppBar包裹BottomNavigationBar

两个底部组件嵌套叠加,导致布局高度异常,FAB位置完全错位。
第二次尝试:调整BottomAppBar高度匹配BottomNavigationBar

强制设置高度后,BottomNavigationBar的内部布局逻辑仍与BottomAppBar不兼容,无法形成适配FAB的凹口,导航项排列存在偏差。
正确解决方案
放弃嵌套BottomNavigationBar,改用BottomAppBar作为底部容器,内部通过Row实现导航项,配合凹口形状和正确的FAB位置,即可实现目标效果:
floatingActionButton: FloatingActionButton( onPressed: () { // 添加FAB点击逻辑 }, child: Icon(Icons.add), backgroundColor: Color(0xFF0066EE), ), floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked, bottomNavigationBar: BottomAppBar( color: Color(0xFF0066EE), shape: CircularNotchedRectangle(), // 生成适配FAB的圆形凹口 child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ // 左侧导航项 IconButton( icon: Icon(Icons.home, color: Colors.white), onPressed: () { // Home页面跳转逻辑 }, ), IconButton( icon: Icon(Icons.book, color: Colors.white), onPressed: () { Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) { final foodItemsModel = Provider.of<FoodItemsModel>(context, listen: false); return MealPlanPage(mealList: foodItemsModel.foodItems); }, ), ); }, ), // 占位符,对应FAB位置,保证导航项对称 SizedBox(width: 48), // 右侧导航项 IconButton( icon: Icon(Icons.spoke_rounded, color: Colors.white), onPressed: () { Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) { return PlanPage(); }, ), ); }, ), IconButton( icon: Icon(Icons.more, color: Colors.white), onPressed: () { // More页面跳转逻辑 }, ), ], ), ),
关键说明
- 凹口生成:通过
shape: CircularNotchedRectangle()让BottomAppBar自动在FAB位置生成适配的圆形凹口。 - 对称布局:在FAB对应位置添加
SizedBox(width: 48)(FAB默认宽度),保证左右导航项均匀分布。 - FAB位置:使用
FloatingActionButtonLocation.centerDocked,让FAB一半嵌入BottomAppBar,一半悬浮在外,符合设计预期。
内容的提问来源于stack exchange,提问作者Matthew Segura
相关产品推荐
相关产品推荐

