Flutter中如何修改NavigationDestination的标签颜色?
NavigationBar的标签样式不受全局TextTheme控制,因为它有自己独立的样式配置优先级。你可以通过以下两种方式修改标签颜色:
方式一:直接在NavigationBar组件内配置
通过labelTextStyle参数,结合MaterialStateProperty.resolveWith区分选中/未选中状态,自定义文本颜色:
NavigationBar( labelBehavior: NavigationDestinationLabelBehavior.onlyShowSelected, selectedIndex: currentIndex, onDestinationSelected: onTap, // 自定义标签文本样式 labelTextStyle: MaterialStateProperty.resolveWith<TextStyle>((states) { // 选中状态下使用白色 if (states.contains(MaterialState.selected)) { return const TextStyle(color: ColorPalette.white, fontSize: 14); } // 未选中状态(如需显示可配置对应颜色) return const TextStyle(color: ColorPalette.gray, fontSize: 14); }), destinations: const <Widget>[ NavigationDestination( icon: Icon(Icons.home_outlined, color: ColorPalette.gray), selectedIcon: Icon(Icons.home_rounded, color: ColorPalette.white), label: "Home", ), NavigationDestination( icon: Icon(Icons.playlist_add_outlined, color: ColorPalette.gray), selectedIcon: Icon(Icons.playlist_add_rounded, color: ColorPalette.white), label: 'Playlists', ), NavigationDestination( icon: Icon(Icons.person_outline_rounded, color: ColorPalette.gray), selectedIcon: Icon(Icons.person_rounded, color: ColorPalette.white), label: 'Profile', ), ], backgroundColor: ColorPalette.darkGreen, indicatorColor: ColorPalette.green, );
方式二:全局Theme配置(统一所有NavigationBar样式)
如果你的应用中有多个NavigationBar,想要统一样式,可以在MaterialApp的theme中配置NavigationBarThemeData:
MaterialApp( theme: ThemeData( navigationBarTheme: NavigationBarThemeData( labelTextStyle: MaterialStateProperty.resolveWith<TextStyle>((states) { return states.contains(MaterialState.selected) ? const TextStyle(color: ColorPalette.white) : const TextStyle(color: ColorPalette.gray); }), // 还可按需配置iconTheme、backgroundColor等其他样式 ), ), home: YourHomePage(), );
补充说明
修改全局TextTheme无效的原因是:NavigationBar的标签样式优先级高于全局文本主题,组件自身的labelTextStyle或全局NavigationBarThemeData会直接覆盖TextTheme的配置。
内容的提问来源于stack exchange,提问作者Capital Nerd
相关产品推荐
相关产品推荐

