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.
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):Setting
and
For a specific and limited number of widgets, wrapping them in a widget IgnorePointer does exactly this: when its
ignoring
property is set to true, the sub-widget (actually, the entire subtree) is not clickable.Otherwise, if you intend to disable an entire subtree, look into AbsorbPointer().
Enable and Disable functionality is same for most of the widgets.
Ex, button , switch, checkbox etc.
Just set the
onPressed
property as shown belowonPressed : null
returns Disabled widgetonPressed : (){}
oronPressed : _functionName
returns Enabled widgetThe simple answer is
onPressed : null
gives a disabled button.According to the docs:
"If the onPressed callback is null, then the button will be disabled and by default will resemble a flat button in the disabledColor."
https://docs.flutter.io/flutter/material/RaisedButton-class.html
So, you might do something like this: