Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the onPressed elevation in ElevatedButton Flutter

Before version 2.0.1 of flutter I was using the RaisedButton and there was a property called focusElevation to change the elevation of the button for when it was pressed. So after deprecating it by Flutter and according to the documentations we should use the ElevatedButton instead. But now I can't find a way to change it with the style: property.

I know how to change the elevation but I want to change the onPressed elevation for when user presses it. As comes from its documentations there are some default values for it:

The button's elevations are defined relative to the elevation parameter. The disabled elevation is the same as the parameter value, elevation + 2 is used when the button is hovered or focused, and elevation + 6 is used when the button is pressed.

So any idea how to customize the onPressed elevation in ElevatedButton?

like image 685
Taba Avatar asked Jun 14 '26 03:06

Taba


1 Answers

You can do it using the style property.

ElevatedButton(
  style: ButtonStyle(
    elevation: MaterialStateProperty.resolveWith<double>(
      (Set<MaterialState> states) {
        // if the button is pressed the elevation is 10.0, if not
        // it is 5.0
        if (states.contains(MaterialState.pressed))
          return 10.0;
        return 5.0;
      },
    ),
  ),
)

Or you can combine it with the new ElevatedButton.styleFrom() property, by usign the merge method. Like this:

ElevatedButton.styleFrom(primary: Colors.red).merge(
              ButtonStyle(
                elevation: MaterialStateProperty.resolveWith<double>(
                  (Set<MaterialState> states) {
                    if (states.contains(MaterialState.pressed))
                      return 10.0;
                    return 5.0;
                  },
                ),
              ),
            ),
          ),
like image 69
Andrej Avatar answered Jun 15 '26 22:06

Andrej



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!