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

Flutter中自定义Bottom Navigation Bar选中项背景高亮实现

实现BottomNavigationBar选中项背景色高亮的方案

要实现选中项背景色高亮的效果,原生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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 09:54:19