如何修改Flutter Material3 NavigationBar组件的选中标签文字颜色?
在Material3体系下,你代码里用的是NavigationBar(而非旧版BottomNavigationBar),它的标签样式默认由主题配置控制,直接给NavigationDestination设置文字样式会被组件的选中状态覆盖,所以你之前的尝试没生效。这里提供两种实用的解决方法:
方法一:通过主题全局配置(推荐)
在ThemeData里针对NavigationBar单独配置选中/未选中的标签样式,所有NavigationDestination会自动应用该规则:
// 可以在MaterialApp或父级Theme中设置主题 Theme( data: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue), navigationBarTheme: NavigationBarThemeData( labelTextStyle: MaterialStateProperty.resolveWith<TextStyle>( (Set<MaterialState> states) { // 根据组件状态返回对应样式 if (states.contains(MaterialState.selected)) { return TextStyle( color: HexColor('FF0000'), // 自定义选中时的文字颜色 fontWeight: FontWeight.w600, ); } return TextStyle( color: HexColor('999999'), // 自定义未选中时的文字颜色 ); }, ), ), ), child: Scaffold( bottomNavigationBar: NavigationBar( onDestinationSelected: (int index) { setState(() { currentPageIndex = index; }); }, indicatorColor: HexColor('CEE7EF'), backgroundColor: HexColor('ffffff'), labelBehavior: labelBehavior, selectedIndex: currentPageIndex, destinations: const <Widget>[ NavigationDestination( selectedIcon: Icon(Icons.home), icon: Icon(Icons.home_outlined), label: 'Home', ), NavigationDestination( icon: Icon(Icons.important_devices), label: 'Devices', ), NavigationDestination( icon: Icon(Icons.settings), label: 'Settings', ), ], ), // ... 页面其他内容 ), )
方法二:单独定制每个NavigationDestination
如果不需要全局统一样式,可以把NavigationDestination的默认标签替换为自定义Text组件,根据选中索引动态切换颜色:
bottomNavigationBar: NavigationBar( onDestinationSelected: (int index) { setState(() { currentPageIndex = index; }); }, indicatorColor: HexColor('CEE7EF'), backgroundColor: HexColor('ffffff'), labelBehavior: labelBehavior, selectedIndex: currentPageIndex, destinations: <Widget>[ NavigationDestination( selectedIcon: Icon(Icons.home, color: currentPageIndex == 0 ? HexColor('FF0000') : null), icon: Icon(Icons.home_outlined, color: currentPageIndex != 0 ? HexColor('999999') : null), label: '', child: Text( 'Home', style: TextStyle( color: currentPageIndex == 0 ? HexColor('FF0000') : HexColor('999999'), ), ), ), NavigationDestination( icon: Icon(Icons.important_devices, color: currentPageIndex != 1 ? HexColor('999999') : HexColor('FF0000')), label: '', child: Text( 'Devices', style: TextStyle( color: currentPageIndex == 1 ? HexColor('FF0000') : HexColor('999999'), ), ), ), NavigationDestination( icon: Icon(Icons.settings, color: currentPageIndex != 2 ? HexColor('999999') : HexColor('FF0000')), label: '', child: Text( 'Settings', style: TextStyle( color: currentPageIndex == 2 ? HexColor('FF0000') : HexColor('999999'), ), ), ), ], ),
两种方法中,方法一更贴合Material3的设计规范,维护成本更低;方法二更灵活,适合需要单独定制某几个标签的场景。
内容的提问来源于stack exchange,提问作者skrocket18
相关产品推荐
相关产品推荐

