BottomNavigationItem设置背景色不生效,如何正确修改?
问题原因
你设置的BottomNavigationBarItem的backgroundColor属性未生效,是因为默认情况下外层BottomNavigationBar的type为BottomNavigationBarType.fixed,该模式下会忽略单个item的背景色配置,只有type设为BottomNavigationBarType.shifting时该属性才会生效。
方案1:使用自带shifting模式(适合无圆角的满背景效果)
直接修改外层BottomNavigationBar的配置即可,示例代码如下:
int _currentIndex = 0; // 记录当前选中的tab索引 BottomNavigationBar( // 必须添加该行配置,item的backgroundColor才会生效 type: BottomNavigationBarType.shifting, selectedItemColor: Colors.white, unselectedItemColor: Colors.grey, currentIndex: _currentIndex, onTap: (index) { setState(() { _currentIndex = index; }); }, items: [ BottomNavigationBarItem( icon: SvgPicture.asset("assets/icons/tinpay3.svg", color: Colors.grey), activeIcon: SvgPicture.asset("assets/icons/tinpay3.svg", color: Colors.white), label: "TINPAY", backgroundColor: Color.fromRGBO(255, 194, 44, 1.0), ), // 其他tab的BottomNavigationBarItem配置 ], )
方案2:自定义icon样式(适合带圆角的选中背景效果)
如果你需要实现示例中的圆角高亮背景效果,更推荐直接自定义item的icon组件,灵活度更高,不需要依赖shifting模式:
int _currentIndex = 0; // 记录当前选中的tab索引 BottomNavigationBar( type: BottomNavigationBarType.fixed, backgroundColor: Colors.white, // 导航栏全局背景色 selectedItemColor: Color.fromRGBO(255, 194, 44, 1.0), unselectedItemColor: Colors.grey, currentIndex: _currentIndex, onTap: (index) { setState(() { _currentIndex = index; }); }, items: [ BottomNavigationBarItem( icon: Container( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6), decoration: _currentIndex == 0 ? BoxDecoration( color: Color.fromRGBO(255, 194, 44, 1.0), borderRadius: BorderRadius.circular(20), ) : null, child: SvgPicture.asset( "assets/icons/tinpay3.svg", color: _currentIndex == 0 ? Colors.white : Colors.grey, ), ), label: "TINPAY", ), // 其他tab的BottomNavigationBarItem配置,注意修改判断的索引值即可 ], )
注意事项
- 方案1的shifting模式要求所有item都设置
backgroundColor,否则切换tab时会出现透明背景的问题 - 方案2可以自定义背景的圆角大小、padding、形状,适配性更强
内容的提问来源于stack exchange,提问作者Brutal
相关产品推荐
相关产品推荐

