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

Flutter中如何修改NavigationDestination的标签颜色?

解决Flutter NavigationBar标签颜色修改问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 08:46:22