Flutter ChoiceChip 选定的文本颜色

问题描述 投票:0回答:3

如何使用 ChoiceChip 小部件为所选芯片的文本设置特定颜色? “selectedColor”只是设置所选芯片的背景颜色。

flutter widget
3个回答
8
投票

使用

labelStyle
属性设置
ChoiceChip
的文本颜色。

ChoiceChip(
  label: Text('Hi'),
  selected: isSelected,
  labelStyle: TextStyle(
    color: isSelected ? Colors.blue : Colors.red,
  ),
),

6
投票

以防万一将来有人遇到此问题并想要使用主题来设置所选标签文本颜色:

ThemeData example = ThemeData(
  chipTheme: ChipThemeData(
      showCheckmark: false,
      backgroundColor: Colors.transparent,
      selectedColor: Colors.blue,
      labelStyle: const TextStyle(
          color: ChipLabelColor()
      )
  ),
);

class ChipLabelColor extends Color
    implements MaterialStateColor {
  const ChipLabelColor() : super(_default);

  static const int _default = 0xFF000000;

  @override
  Color resolve(Set<MaterialState> states) {
    if (states.contains(MaterialState.selected)) {
      return Colors.white; // Selected text color
    }
    return Colors.black; // normal text color
  }
}

此示例创建一个具有黑色文本(和透明背景)的芯片,当选择该芯片(具有蓝色背景)时,该芯片会变为白色

MaterialStateColor 类记录在此处,其中包含类似于上述代码的示例。虽然整个标签不能使用材质状态属性,但我发现标签颜色接受材质状态类来解析不同的状态。


0
投票
添加

lilpomm的答案,如果您想使用Theme

,您只需使用
secondaryLabelStyle
即可。
来自其文档:

覆盖 [ChoiceChip.labelStyle] 的默认样式,即包含芯片标签的 [DefaultTextStyle] 的样式。 这只对尊重 [DefaultTextStyle] 的标签小部件有影响,例如 [Text]。

这样您就可以编辑选定的文本颜色,以及其他样式属性:

ThemeData example = ThemeData( chipTheme: ChipThemeData( backgroundColor: Colors.white, selectedColor: Colors.black, secondaryLabelStyle: const TextStyle( color: Colors.white, fontWeight: FontWeight.bold, ), ), );
    
© www.soinside.com 2019 - 2024. All rights reserved.