Flutter修改NavigationBar选中时labelTextStyle颜色方法
问题原因
NavigationBarTheme 完全支持选中状态下单独配置标签文字样式。你当前配置下所有文字固定为灰色,是因为labelTextStyle使用了MaterialStateProperty.all()构造方法,该方法会忽略导航项的所有交互状态,全场景返回你写死的灰色文本样式,自然无法区分选中、未选中效果。
修复方案
将MaterialStateProperty.all()替换为MaterialStateProperty.resolveWith(),根据组件当前的状态集合动态返回对应样式:判断状态集合中是否包含MaterialState.selected,选中状态返回配置了目标高亮色的文本样式,未选中状态返回原来的灰色样式即可。
完整配置代码参考:
bottomNavigationBar: NavigationBarTheme( data: NavigationBarThemeData( height: 65, indicatorColor: Colors.transparent, backgroundColor: Colors.white, // 替换原来的MaterialStateProperty.all配置 labelTextStyle: MaterialStateProperty.resolveWith((states) { // 选中状态的文本样式 if (states.contains(MaterialState.selected)) { return const TextStyle( fontSize: 13.0, fontWeight: FontWeight.w700, color: Colors.blue, // 替换为你需要的选中态文字颜色 letterSpacing: 1.0, ); } // 未选中状态的文本样式 return const TextStyle( fontSize: 13.0, fontWeight: FontWeight.w700, color: Colors.grey, letterSpacing: 1.0, ); }), ), // 此处接原有NavigationBar组件及导航项配置 child: NavigationBar( // 你的原有导航项逻辑 ), )
优化建议
- 可以把字号、字重、字间距这类公共样式抽成公共常量,不同状态下仅修改
color属性,减少重复代码。 - 如果需要全局生效该导航栏样式,可以把上述
NavigationBarThemeData配置到App根主题ThemeData的navigationBarTheme参数中,无需每个页面单独包裹NavigationBarTheme组件。
内容的提问来源于stack exchange,提问作者Lils Don
相关产品推荐
相关产品推荐

