I'm just starting to get the hang of Flutter, but I'm having trouble figuring out how to set the enabled state of a button.
From the docs, it says to set onPressed
to null to disable a button, and give it a value to enable it. This is fine if the button continues to be in the same state for the lifecycle.
I get the impression I need to create a custom Stateful widget that will allow me to update the button's enabled state (or onPressed callback) somehow.
So my question is how would I do that? This seems like a pretty straightforward requirement, but I can't find anything in the docs on how to do it.
Thanks.
Best Answer
I think you may want to introduce some helper functions to
build
your button as well as a Stateful widget along with some property to key off of.isButtonDisabled
)onPressed
value to eithernull
or some functiononPressed: () {}
isButtonDisabled
as part of this conditional and return eithernull
or some function.setState(() => isButtonDisabled = true)
to flip the conditional variable.build()
method again with the new state and the button will be rendered with anull
press handler and be disabled.Here's is some more context using the Flutter counter project.
In this example I am using an inline ternary to conditionally set the
Text
andonPressed
, but it may be more appropriate for you to extract this into a function (you can use this same method to change the text of the button as well):