51

I have a question related with the new ElevatedButtonThemeData widget, basically I want to set the background color for all ElevatedButtons in my app, I'm struggling trying to set it up in the ThemeData definition by doing:

      theme: ThemeData(
        ...
        elevatedButtonTheme: ElevatedButtonThemeData(
            style: ButtonStyle(backgroundColor: Colors.red)), // Here Im having the error
        ...
        ),
      ),

Error:

The argument type 'MaterialColor' can't be assigned to the parameter type 'MaterialStateProperty<Color?>?'.dartargument_type_not_assignable)

5 Answers 5

91

After reading the documentation I found the way to set the color.

  theme: ThemeData(
    ...
    elevatedButtonTheme: ElevatedButtonThemeData(
        style: ButtonStyle(backgroundColor: MaterialStateProperty.all<Color>(Colors.red))), // Here Im having the error
    ...
    ),
  ),
1
  • 3
    This works perfectly!
    – Petro
    Nov 19, 2021 at 20:38
31

Here is a code snippet that shows how I have styled a text button, by using material state properties.

You can see how can you add different types of values:

TextButton(style: ButtonStyle(
      padding: MaterialStateProperty.all(const EdgeInsets.all(0)),
      elevation: MaterialStateProperty.all(8),
      shape: MaterialStateProperty.all(
          RoundedRectangleBorder(borderRadius: BorderRadius.circular(50))),
      backgroundColor: MaterialStateProperty.all(Colors.blue),
      shadowColor: MaterialStateProperty.all(
          Theme.of(context).colorScheme.onSurface),
    ),),

I hope this gives you an idea.

To know more about MaterialStateProperty, you can go for this official video: MaterialStateProperties | Decoding Flutter

10

Instead of using ButtonStyle() try:

style: ElevatedButton.styleFrom(backgroundColor: Colors.red)
1
  • 3
    This is a proper answer for a one-time. .styleFrom() is handy in flutter!
    – vladli
    Jan 20 at 11:35
8
MaterialStateProperty.all<Color>(Colors.red)

This returns MaterialStateProperty<Color?> data type.

2

Before:

backgroundColor: Colors.green,

After:

backgroundColor: MaterialStateProperty.all<Color>(Colors.green),

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.