Flutter中自定义Bottom Navigation Bar选中项背景高亮实现
要实现选中项背景色高亮的效果,原生BottomNavigationBar并不支持直接设置选中项的背景色,我们可以通过自定义底部导航栏的布局来达成需求,以下是修改后的完整代码:
int _selectedIndex = 0; void _onItemTapped(int index) { setState(() { _selectedIndex = index; }); } // ... 其他页面代码 bottomNavigationBar: BottomAppBar( color: Colors.white, elevation: 8, child: SizedBox( height: 60, child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ _buildNavItem(Icons.home_outlined, 0), _buildNavItem(Icons.checklist_outlined, 1), _buildNavItem(Icons.file_copy_outlined, 2), _buildNavItem(Icons.notifications_outlined, 3), _buildNavItem(Icons.settings_outlined, 4), ], ), ), ), // 自定义导航项方法 Widget _buildNavItem(IconData icon, int index) { bool isSelected = _selectedIndex == index; return Expanded( child: InkWell( onTap: () => _onItemTapped(index), borderRadius: BorderRadius.circular(8), child: Container( alignment: Alignment.center, decoration: isSelected ? BoxDecoration( color: Colors.blue.shade100, // 选中时的背景色,可按需修改 borderRadius: BorderRadius.circular(8), ) : null, child: Icon( icon, color: isSelected ? Colors.blue : Colors.grey, // 图标颜色随选中状态切换 size: 24, ), ), ), ); }
关键说明:
- 用
BottomAppBar替代原生BottomNavigationBar作为容器,更便于自定义整体样式 - 每个导航项通过
Expanded平分底部栏宽度,保证布局均匀 - 用
InkWell处理点击事件,同时提供Material风格的水波纹交互效果 - 根据
_selectedIndex动态切换选中项的背景色和图标颜色,你可以自由调整背景色、圆角大小等样式参数 - 可通过修改
SizedBox的height值调整底部栏的整体高度
内容的提问来源于stack exchange,提问作者Prashant
相关产品推荐
相关产品推荐

