Hi I’m new to flutter and I want to apply disabled color and full-screen width to ElevatedButton.
So for applying color, I did like this:
ElevatedButton(
style : ButtonStyle(
backgroundColor : MaterialStateProperty.resolveWith<Color>(
(Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {return Colors.green;}
else {return Colors.blue;}
}
),
...
And for applying width, I did like this:
ElevatedButton(
style : ElevatedButton.styleFrom(
minimumSize : const Size.fromHeight(50)
),
...
But I have no idea how can I combine them. Please tell me.
Thanks,
3
Answers
You can set
minimumSize
inButtonStyle
too, like this:You can use
merge
extensionWith this approach, you’ll be able to use both the
minimumSize
andbackgroundColor
properties for yourElevatedButton
.You can also use other properties that
ElevatedButton.styleFrom()
andButtonStyle()
have and combine them as you want.The
style
property is used to customize the appearance of the button. First, it uses theElevatedButton.styleFrom()
method to create a newButtonStyle
object, and sets theminimumSize
property toSize.fromHeight(40)
, which means that the button will have a minimum height of 40.Then, it uses the
merge()
method to merge the newly createdButtonStyle
object with an existingButtonStyle
object. This allows you to customize the style of the button without overwriting the existing styles.It then uses the
backgroundColor
property to set the background color of the button based on its enabled/disabled state by usingMaterialStateProperty.resolveWith
method, which allows you to provide a callback that returns a different color based on the button’sMaterialState
.This callback checks if the button is in the disabled state by checking if the MaterialState.disabled is present in the states set, if it is present it returns the color grey else it returns the color blue.
Finally, it sets the child property to a Text widget with the text "Action Title", which is displayed on the button.
The button will be rendered with a disabled state, and its background color will be grey and its minimum height will be 40, and it will display the text "Action Title"
You can pass null to the
onPressed
property to see the button disable state.