Chloé
Chloé

Reputation: 1129

Flutter ChoiceChip selected Text color

How to set a specific color to the text of the selected chip with a ChoiceChip widget ? "selectedColor" is only setting the background color of the selected chip.

Upvotes: 7

Views: 7947

Answers (3)

Lostsaka
Lostsaka

Reputation: 308

Adding to lilpomm's answer, if you want to use a Theme you can simply just use a secondaryLabelStyle. From its documentation:

Overrides the default for [ChoiceChip.labelStyle], the style of the [DefaultTextStyle] that contains the chip's label. This only has an effect on label widgets that respect the [DefaultTextStyle], such as [Text].

So this way you can edit the selected text color, as well as the other style attributes:

ThemeData example = ThemeData(
  chipTheme: ChipThemeData(
      backgroundColor: Colors.white,
      selectedColor: Colors.black,
      secondaryLabelStyle: const TextStyle(
        color: Colors.white,
        fontWeight: FontWeight.bold,
      ),
  ),
);

Upvotes: 1

lilpomm
lilpomm

Reputation: 101

Just in case someone comes across this in the future and wants to use themes to set the selected label text color:

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
  }
}

This example creates a chip that has black text (and a transparent background) that changes to white when the chip is selected (with a blue background)

The MaterialStateColor class is documented here with an example that resembles the above code. While the entire label cant use material state property I found that the label color was accepting of the material state class to resolve with the different states.

Upvotes: 8

Tirth Patel
Tirth Patel

Reputation: 5746

Use labelStyle property to set text-color of ChoiceChip.

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

Upvotes: 12

Related Questions