简体   繁体   中英

How to change background color of Elevated Button in Flutter from function?

I am new to Flutter, I started Flutter last week, And now I want to make a simple Xylophone app. 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<dynamic>' is not a subtype of type 'MaterialStateProperty<Color?>?'**

Here's the code I wrote for 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 to call this function because it gives me the above-mentioned error?

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

Using styleFrom to style an ElevatedButton:

ElevatedButton(
      child: Text('Button'),
      onPressed: () {},
      style: ElevatedButton.styleFrom({
           Color primary, // set the background color 
           Color onPrimary, 
           Color onSurface, 
           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(
                primary: 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))),
),

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

高架按钮

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

Reference:

ElevatedButton class

ElevatedButton(onPressed: resetHandler,
               child: Text("button"),
               style: ElevatedButton.styleFrom(primary: Colors.amber),),

You have 3 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.
      },
    ),
  ),
)

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),
)

Screenshot:

在此处输入图像描述


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(
            primary: _flag ? Colors.red : Colors.teal, // This is what you need!
          ),
        ),
      ),
    );
  }
}
style: ElevatedButton.styleFrom(primary : Colors.black),
 style: ElevatedButton.styleFrom(
                        shape: RoundedRectangleBorder(
                          borderRadius: new BorderRadius.circular(30.0),
                        ),
                          primary: HexColor(HexColor.primarycolor),
                          textStyle: TextStyle(fontWeight: FontWeight.bold)),
ElevatedButton(
          onPressed: (){},
          child: Text('comprar'),
          style: ElevatedButton.styleFrom(
            primary: Theme.of(context).primaryColor
          )
        )

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'),
        ),
style: ButtonStyle({  
  MaterialStateProperty.all(backgroundColor),   
),

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

Make sure to add onPressed: () {},

otherwise color will be gray

want to change the elevated button background color and outline color also with 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: - 在此处输入图像描述

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()
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM