mef27
mef27

Reputation: 409

Change the text color of an ElevatedButton in Flutter with ButtonStyle

I want a button that:

I'm trying to achieve this with the ButtonStyle class.

ElevatedButton(
  child: Text("Example"),
  onPressed: onPressed, // onPressed is a function
  style: ButtonStyle(
    backgroundColor: MaterialStateProperty.resolveWith((states) {
      if (states.contains(MaterialState.disabled)) { return KPColors.offWhite; }
      if (states.contains(MaterialState.pressed)) { return KPColors.primaryLight; }
      return KPColors.primaryExtraLight;
    }),
    textStyle: MaterialStateProperty.resolveWith((states) {
      Color textColor = states.contains(MaterialState.disabled) ? KPColors.gray : KPColors.primary;
      return TextStyle(fontSize: 18, color: textColor);
    }),
    overlayColor: MaterialStateProperty.all(KPColors.clear), // prevents the shimmer effect when pressing the button
    shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(16))), // Rounds the corners
    elevation: MaterialStateProperty.all(0), // Prevents shadow around button
  ),
),

The code succeeds in changing the background color of the button, but not the text color, which appears white instead of my custom color. I think this is because ElevatedButton's child is a Text widget, which has a default text color which is overriding mine.

How can I solve this? I already know that I can change the text color of the button by using ElevatedButton.styleFrom(...) and setting the onPrimary property, instead of ButtonStyle, but this would make it much more difficult to have different colors depending on the pressed and disabled states of the button.

Upvotes: 1

Views: 2519

Answers (2)

Javad Zobeidi
Javad Zobeidi

Reputation: 191

you can use ElevatedButton.styleFrom

ElevatedButton(
  child: Text("Example",style:TextStyle(color:isActive ? Colors.white : Colors.black)),
  onPressed: isActive ? (){print('do somthing');} : (){}, // onPressed is a function
  style: ElevatedButton.styleFrom(primary: isActive ? Colors.blue : Colors.grey),
        )


Upvotes: 0

Er1
Er1

Reputation: 2758

you need to set the foregroundColor in the ButtonStyle

For example:

foregroundColor: MaterialStateProperty.resolveWith((states) {
      if (states.contains(MaterialState.disabled)) { return Colors.grey; }
      if (states.contains(MaterialState.pressed)) { return Colors.green; }
      return Colors.blue;
    })

Upvotes: 1

Related Questions