How can I change the background color of Elevated Button in Flutter from function?
Asked Answered
J

19

211

I am new to Flutter, and I started Flutter last week. And now I want to make a simple Xylophone application. I created the UI successfully and made a function playSound(int soundNumber), but when I call this function for playing sound, it gives me this error.

The following _TypeError was thrown building Body(dirty, state: _BodyState#051c2):
type '_MaterialStatePropertyAll' is not a subtype of type 'MaterialStateProperty<Color?>?'

Here's the code I wrote for the playSound(int soundNumber) function.

void playSound(int soundNumber) {
  final player = AudioCache();
  player.play('note$soundNumber.wav');
}

Expanded buildPlayButton({MaterialStateProperty color, int soundNumber}) {
  return Expanded(
    child: ElevatedButton(
      onPressed: () {
        playSound(soundNumber);
      },
      style: ButtonStyle(
        backgroundColor: color,
      ),
    ),
  );
}

Here is the point where I am calling this function.

Widget build(BuildContext context) {
  return Column(
    crossAxisAlignment: CrossAxisAlignment.stretch,
    children: <Widget>[
      buildPlayButton(color: MaterialStateProperty.all(Colors.red), soundNumber: 1),
      buildPlayButton(color: MaterialStateProperty.all(Colors.orangeAccent), soundNumber: 2),
      buildPlayButton(color: MaterialStateProperty.all(Colors.yellow), soundNumber: 3),
      buildPlayButton(color: MaterialStateProperty.all(Colors.indigo), soundNumber: 4),
      buildPlayButton(color: MaterialStateProperty.all(Colors.blue), soundNumber: 5),
      buildPlayButton(color: MaterialStateProperty.all(Colors.lightGreenAccent), soundNumber: 6),
      buildPlayButton(color: MaterialStateProperty.all(Colors.green), soundNumber: 7),
    ],
  );
}

How can I call this function, because it gives me the above-mentioned error?

Janeanjaneczka answered 27/3, 2021 at 19:11 Comment(0)
N
300

You can style ElevatedButton by using the styleFrom static method or the ButtonStyle class. The first one is more convenient than the second one.

Using styleFrom to style an ElevatedButton:

ElevatedButton(
      child: Text('Button'),
      onPressed: () {},
      style: ElevatedButton.styleFrom({
           Color backgroundColor, // set the background color
           Color foregroundColor,
           Color disabledForegroundColor,
           Color shadowColor,
           double elevation,
           TextStyle textStyle,
           EdgeInsetsGeometry padding,
           Size minimumSize,
           BorderSide side,
           OutlinedBorder shape,
           MouseCursor enabledMouseCursor,
           MouseCursor disabledMouseCursor,
           VisualDensity visualDensity,
           MaterialTapTargetSize tapTargetSize,
           Duration animationDuration,
           bool enableFeedback
     }),
),

Example:

ElevatedButton(
            child: Text('Button'),
            onPressed: () {},
            style: ElevatedButton.styleFrom(
                backgroundColor: Colors.purple,
                padding: EdgeInsets.symmetric(horizontal: 50, vertical: 20),
                textStyle: TextStyle(
                fontSize: 30,
                fontWeight: FontWeight.bold)),
),

Using ButtonStyle to style an ElevatedButton:

style: ButtonStyle({
  MaterialStateProperty<TextStyle> textStyle,
  MaterialStateProperty<Color> backgroundColor,
  MaterialStateProperty<Color> foregroundColor,
  MaterialStateProperty<Color> overlayColor,
  MaterialStateProperty<Color> shadowColor,
  MaterialStateProperty<double> elevation,
  MaterialStateProperty<EdgeInsetsGeometry> padding,
  MaterialStateProperty<Size> minimumSize,
  MaterialStateProperty<BorderSide> side,
  MaterialStateProperty<OutlinedBorder> shape,
  MaterialStateProperty<MouseCursor> mouseCursor,
  VisualDensity visualDensity,
  MaterialTapTargetSize tapTargetSize,
  Duration animationDuration,
  bool enableFeedback
})

Example

ElevatedButton(
            child: Text('Button'),
            onPressed: () {},
            style: ButtonStyle(
                backgroundColor: MaterialStateProperty.all(Colors.red),
                padding: MaterialStateProperty.all(EdgeInsets.all(50)),
                textStyle: MaterialStateProperty.all(TextStyle(fontSize: 30))),
),
Nubianubian answered 22/4, 2021 at 10:31 Comment(3)
Thanks for the answer, but I do not understand why I cannot do Theme.of(context).elevatedButtonTheme.copyWith(backgroundColor: ...) The elevatedButtonTheme is null at runtime. I do not get why, as other themes aren't null...Pincas
property "primary" to set the background color is deprecated now. Use "backgroundColor" instead.Herefordshire
getting error 'primary' is deprecated and shouldn't be used. Use backgroundColor instead. This feature was deprecated after v3.1.0. Try replacing the use of the deprecated member with the replacement.Strata
L
78

Pass color as parameter and use MaterialStateProperty.all<Color>(color) to specify the color.

buildPlayButton(color: Colors.red, soundNumber: 1)
Expanded buildPlayButton({Color color, int soundNumber}){
  return Expanded(
    child: ElevatedButton(
      onPressed: () {
        playSound(soundNumber);
      },
      style: ButtonStyle(
        backgroundColor: MaterialStateProperty.all<Color>(color),
      ),
    ),
);}

Sample button

Elevated Button

In general

ElevatedButton(
  style: ElevatedButton.styleFrom(
    primary: Colors.red, // background
    onPrimary: Colors.yellow, // foreground
  ),
  onPressed: () {},
  child: Text('ElevatedButton with custom foreground/background'),
)

Sample button

ElevatedButton with custom foreground/background

Reference:

ElevatedButton class

Little answered 27/3, 2021 at 19:21 Comment(4)
which arguments i have to pass when adding this inside a function?Janeanjaneczka
I've updated the post. Pass color as parameter and use MaterialStateProperty.all<Color>(color) to specify the color.Little
thanks @Little ... it worked like a charm...Janeanjaneczka
primary and onPrimary no longer exist. See https://mcmap.net/q/126072/-how-can-i-change-the-background-color-of-elevated-button-in-flutter-from-functionUrgent
D
19
ElevatedButton(onPressed: resetHandler,
               child: Text("button"),
               style: ElevatedButton.styleFrom(primary: Colors.amber),),
Dovekie answered 27/3, 2021 at 19:49 Comment(3)
style:Elevatedbutton.styleFrom(primary:Colors.amber)Dovekie
getting error - 'primary' is deprecated and shouldn't be used. Use backgroundColor instead. This feature was deprecated after v3.1.0. Try replacing the use of the deprecated member with the replacement.Strata
primary and onPrimary no longer exist. See https://mcmap.net/q/126072/-how-can-i-change-the-background-color-of-elevated-button-in-flutter-from-functionUrgent
S
17

Just use MaterialStateProperty.all(**YOUR COLOR**):

ElevatedButton(
            child: Text('Button'),
            onPressed: () {},
            style: ButtonStyle(
                backgroundColor: MaterialStateProperty.all(Colors.red),)
),

or like this: Just use ElevatedButton.styleFrom(primary: **YOUR COLOR**):

ElevatedButton(
            child: Text('Button'),
            onPressed: () {},
            style: ElevatedButton.styleFrom(primary: Colors.red),
)

Sarette answered 21/1, 2022 at 21:53 Comment(1)
G
14

You have three options to change the background color:

ElevatedButton.styleFrom:

If you just want to change the background color and foreground color irrespective of the states then you can do as given below.

ElevatedButton(
  style: ElevatedButton.styleFrom(
    primary: Colors.red, // Background
    onPrimary: Colors.white, // Foreground
  ),
  onPressed: () { },
  child: Text('custom foreground/background'),
)

MaterialStateProperty.all:

to override a ElevatedButtons default background(text/icon) color for all states.

 ElevatedButton(style:
    ButtonStyle(
      backgroundColor: MaterialStateProperty.all(Colors.red),
    onPressed: () { },
    child: Text('custom foreground/background'),
    ));

MaterialStateProperty.resolveWith:

By default, the elevated button inherits a blue color. We can tweak the default style using the style parameter and ButtonStyle class. Button has different states such as pressed, disabled, hovered, etc. You can change the style for each state. In the below snippet, the default color of the button changes to green when it is pressed.

ElevatedButton(
  style: ButtonStyle(
    backgroundColor: MaterialStateProperty.resolveWith<Color>(
      (Set<MaterialState> states) {
        if (states.contains(MaterialState.pressed))
          return Colors.green;
        return null; // Use the component's default.
      },
    ),
  ),
)
Geraldina answered 1/1, 2022 at 13:18 Comment(1)
E
10

Suppose we need to change Elevated Button Background color then? Elevated Button has a style Property And style property need ButtonStyle(). ButtonStyle has backgroundColor property which requires MaterialStateProperty. You can simply assign background color by MaterialStateProperty.all(Colors.green). Let’s explore examples of Background color of Elevated Button in Flutter.

ElevatedButton(
          onPressed: () {
            print('Button Pressed');
          },
          style: ButtonStyle(
            backgroundColor: MaterialStateProperty.all<Color>(Colors.green),
          ),
          child: Text('Send'),
        ),
Eimile answered 15/6, 2022 at 15:59 Comment(0)
C
10

The current best answer with the example of ElevatedButton.styleFrom is outdated. As of Flutter v3.1.0, the primary parameter is deprecated.

Color? primary // Use foregroundColor instead. This feature was deprecated after v3.1.0.

Instead, use the backgroundColor parameter:

ElevatedButton(
  style: ElevatedButton.styleFrom(
    backgroundColor: const Colors.red,
  ),
  onPressed: () {},
  child: const Text('Test'),
)
Causeway answered 11/10, 2022 at 9:15 Comment(0)
L
7

Screenshot:

enter image description here


Code:

class _MyState extends State<MyPage> {
  bool _flag = true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ElevatedButton(
          onPressed: () => setState(() => _flag = !_flag),
          child: Text(_flag ? 'Red' : 'Green'),
          style: ElevatedButton.styleFrom(
            backgroundColor: _flag ? Colors.red : Colors.teal, // This is what you need!
          ),
        ),
      ),
    );
  }
}
Legitimist answered 17/5, 2021 at 9:46 Comment(0)
G
5

You can simply use this code inside the ElevatedButton

 style: ElevatedButton.styleFrom(
       backgroundColor:Theme.of(context).primaryColor
    ),
Greaves answered 7/10, 2022 at 14:40 Comment(0)
D
5
body:Center(

  child: ElevatedButton(
    onPressed: () {},
     child: Text("click me"),
      style:ButtonStyle(
        backgroundColor: MaterialStateProperty.all(Colors.green))
     ),


  ),

} }

Deckle answered 22/6, 2023 at 5:46 Comment(0)
A
4
 style: ElevatedButton.styleFrom(
                        shape: RoundedRectangleBorder(
                          borderRadius: new BorderRadius.circular(30.0),
                        ),
                          primary: HexColor(HexColor.primarycolor),
                          textStyle: TextStyle(fontWeight: FontWeight.bold)),
Amygdaline answered 23/3, 2022 at 11:33 Comment(0)
C
3
style: ElevatedButton.styleFrom(primary : Colors.black),
Combinative answered 14/5, 2021 at 4:43 Comment(0)
C
3
ElevatedButton(
          onPressed: (){},
          child: Text('comprar'),
          style: ElevatedButton.styleFrom(
            primary: Theme.of(context).primaryColor
          )
        )
Christianity answered 18/7, 2021 at 17:1 Comment(1)
Welcome to Stack Overflow! While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.Physical
F
3

Use styleFrom of ElevatedButton

 ElevatedButton(
      onPressed: (){},
      child: Text('click me'),
      style: ElevatedButton.styleFrom(backgroundColor: Colors.green),
    ),
Finedraw answered 29/5, 2023 at 8:3 Comment(0)
B
2

You need to set the primary property (inside a style) and assign it a color, but be careful, if you haven't set your onPressed() event then the color doesn't change..

Here is an example:

Widget renderMyButton() {
  return ElevatedButton(
      style: ElevatedButton.styleFrom(
        primary: Colors.lightBlue, // Change the color here..
        elevation: 0,
        // ...
      ),

      onPressed: () {}, // This line is important to change the ElevatedButton color..
      child: Container()
  );
}
Betel answered 22/9, 2022 at 14:7 Comment(0)
A
1
style: ButtonStyle({  
  MaterialStateProperty.all(backgroundColor),   
),

Similarly, you can add MaterialStateProperty.all(<Value here>) to most properties of elevated button(elevation, padding, border etc).

Agronomics answered 1/5, 2021 at 15:10 Comment(0)
R
0

Make sure to add onPressed: () {},

Otherwise the color will be gray.

Russophobe answered 21/12, 2021 at 23:36 Comment(2)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Combative
Add where? Can you elaborate?Skier
A
0

If you want to change the elevated button background color and outline color also with the shape of the circle, then checkout this code:

ElevatedButton(
    style: ElevatedButton.styleFrom(
        backgroundColor: Colors.white,
        side: BorderSide(
            width: 1,
            color: primaryBlue),
        shape: RoundedRectangleBorder(
            borderRadius:
                BorderRadius.circular(
          20,
        ))),
    onPressed: () {},
    child: Text(
      'Use camera',
      style: t3b,
    ),
),

This code will look like this:

Enter image description here

Analects answered 22/8, 2022 at 5:24 Comment(0)
T
-1

ElevatedButton( style: ButtonStyle(backgroundColor: MaterialStatePropertyAll(Colors.orange)), onPressed: null,);

Takeover answered 15/10, 2023 at 15:40 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Combative

© 2022 - 2024 — McMap. All rights reserved.