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

Flutter中BottomNavigationBarType为fixed时如何实现选中项背景色切换

问题原因

BottomNavigationBarType.fixed模式下,组件默认优先使用自身的backgroundColor属性作为全局背景,不会读取单个BottomNavigationBarItem的backgroundColor配置,只有shifting模式才会绑定选中项的item背景色到整个导航栏。

实现方案

手动绑定选中索引对应的颜色到BottomNavigationBar的backgroundColor属性即可,操作步骤如下:

  • 提前定义和导航项顺序一一对应的背景色列表
  • 将导航栏type改为BottomNavigationBarType.fixed
  • 给导航栏的backgroundColor属性赋值为当前选中索引对应的背景色
  • 选中索引更新时触发状态刷新即可生效
完整修改后示例代码
// 在State类中定义背景色列表,和导航项顺序一一对应
final List<Color> _navBgColors = const [
  Colors.teal,
  Colors.cyan,
  Colors.lightBlue,
];
int _selectedIndex = 0;

void _onItemTap(int index) {
  setState(() {
    _selectedIndex = index;
  });
}

// 底部导航栏代码
bottomNavigationBar: BottomNavigationBar(
    items: const <BottomNavigationBarItem>[
      BottomNavigationBarItem(
          icon: Icon(Icons.home),
          label: 'Home',
      ),
      BottomNavigationBarItem(
          icon: Icon(Icons.person),
          label: 'Profile',
      ),
      BottomNavigationBarItem(
        icon: Icon(Icons.settings),
        label: 'Settings',
      ),
    ],
    type: BottomNavigationBarType.fixed,
    currentIndex: _selectedIndex,
    // 绑定背景色为当前选中项对应的颜色
    backgroundColor: _navBgColors[_selectedIndex],
    selectedItemColor: Colors.white,
    unselectedItemColor: Colors.grey,
    iconSize: 40,
    onTap: _onItemTap,
    elevation: 5
)
补充说明
  • 原来BottomNavigationBarItem里设置的backgroundColor在fixed模式下不会生效,可直接删除
  • 只要_selectedIndex更新时触发setState刷新,导航栏背景色就会自动切换,同时保留fixed模式的固定无移位动效

内容的提问来源于stack exchange,提问作者cubanGuy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 18:57:03