Sub topic 2
Handling presses and disabling buttons
This chapter covers how Flutter's Material buttons receive presses, how a null callback disables them, and the mistakes that cause a button to stay disabled or to fire at the wrong time. It assumes you know basic Dart (functions and closures), you can build a widget tree with StatelessWidget and StatefulWidget, and you use setState to update the UI. Layout widgets such as Row and Stack appear only in passing.
The callback is the switch
Every Material button (ElevatedButton, FilledButton, OutlinedButton, TextButton, IconButton) takes an onPressed parameter of type VoidCallback?. A VoidCallback is a function with no parameters and no return value. The type is nullable, and that single fact drives the button's behavior:
- If
onPressedis a function, the button is enabled. It responds to taps, shows ink feedback, and reports itself to accessibility services as an actionable control. - If
onPressedisnull, the button is disabled. It ignores taps, draws itself with the disabled colors from the theme, and reports itself as disabled.
There is no separate enabled property. The framework reads the nullability of the callback. This keeps the visual state and the real behavior in sync, because a button can't look enabled while having nothing to run.
The same rule applies to onLongPress. A button with a non-null onLongPress and a null onPressed is still enabled. Only when both callbacks are null does the button become disabled.
A first working press
The simplest enabled button needs a callback and a child. This example uses a StatefulWidget so the label can change after each press.
import 'package:flutter/material.dart';
class CounterButton extends StatefulWidget {
const CounterButton({super.key});
@override
State<CounterButton> createState() => _CounterButtonState();
}
class _CounterButtonState extends State<CounterButton> {
int _count = 0;
@override
Widget build(BuildContext context) {
return FilledButton(
onPressed: () => setState(() => _count++),
child: Text('Pressed $_count times'),
);
}
}When the user taps the button, Flutter calls the closure. The closure calls setState, which runs the increment and marks the widget dirty. The framework then calls build again, and the Text shows the new count.
Note that the increment happens inside the setState callback. Changing _count outside setState would update the field but leave the screen stale until something else triggered a rebuild.
Disabling a button from state
To disable a button conditionally, use a conditional expression that yields either a function or null.
ElevatedButton(
onPressed: _canSubmit ? _submit : null,
child: const Text('Submit'),
)Here _canSubmit is a boolean field in your State class and _submit is a method. Look at what is passed: _submit, not _submit(). The first is a reference to the function. The second would call it during build and pass its return value, which is almost never what you want.
For the button to change when _canSubmit changes, the change must happen inside setState. A typical case is a form where the button enables once a text field has content:
import 'package:flutter/material.dart';
class NameForm extends StatefulWidget {
const NameForm({super.key});
@override
State<NameForm> createState() => _NameFormState();
}
class _NameFormState extends State<NameForm> {
final TextEditingController _controller = TextEditingController();
bool _canSubmit = false;
String _message = '';
@override
void initState() {
super.initState();
_controller.addListener(() {
final canSubmit = _controller.text.trim().isNotEmpty;
if (canSubmit != _canSubmit) {
setState(() => _canSubmit = canSubmit);
}
});
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
void _submit() {
setState(() => _message = 'Hello, ${_controller.text.trim()}!');
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
controller: _controller,
decoration: const InputDecoration(labelText: 'Name'),
),
const SizedBox(height: 12),
ElevatedButton(
onPressed: _canSubmit ? _submit : null,
child: const Text('Submit'),
),
Text(_message),
],
);
}
}The listener only calls setState when the value actually changes. Without that check, every keystroke would rebuild the widget even when the button's state stays the same. The controller is disposed in dispose so the listener does not outlive the widget.
The state flow
The diagram shows how one press cycle moves through the widget and why the disabled state follows from your data.
When the callback runs
A press is not the same as a pointer-down event. Flutter's button uses a tap recognizer internally, and onPressed fires when the finger lifts while still inside the button. Several consequences follow:
- If the user presses down and drags outside the button before releasing, the tap is canceled and
onPresseddoes not run. - If the button sits inside a scrollable and the user starts scrolling, the scroll wins and the tap is canceled. Chapter 11 explains how these competing gestures are resolved.
- A press that lands on a disabled button does nothing. It does not fall through to a widget underneath unless that widget is a separate hit target at the same position.
You can also react to a long press with onLongPress, and to focus or hover with onFocusChange and onHover. These are useful on desktop and web, but onPressed remains the main entry point.
Preventing double submissions
A common bug is a button that triggers an asynchronous task, such as a network call, and lets the user tap it again before the first call finishes. Two requests are sent, two records are created.
The fix uses the same rule: set the callback to null while work is in progress.
import 'package:flutter/material.dart';
class SaveButton extends StatefulWidget {
const SaveButton({super.key, required this.onSave});
final Future<void> Function() onSave;
@override
State<SaveButton> createState() => _SaveButtonState();
}
class _SaveButtonState extends State<SaveButton> {
bool _saving = false;
Future<void> _handlePress() async {
setState(() => _saving = true);
try {
await widget.onSave();
} finally {
if (mounted) {
setState(() => _saving = false);
}
}
}
@override
Widget build(BuildContext context) {
return FilledButton(
onPressed: _saving ? null : _handlePress,
child: Text(_saving ? 'Saving...' : 'Save'),
);
}
}Three details matter here:
setState(() => _saving = true)runs before the firstawait, so the next frame already shows the disabled button. A second tap cannot arrive between the tap and the rebuild in a way that starts another call, because the callback is replaced on the next build.- The
finallyblock restores the state even whenonSavethrows. Without it, a failed save would leave the button disabled forever. - The
mountedcheck guards against the widget being removed from the tree while the future was pending. CallingsetStateon an unmountedStateraises an error.
The finally block restores the button but does not handle the error. If you need to show a message, catch the exception and report it, or let it propagate to your app's error handling.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Button is grey and ignores taps | `onPressed` is `null`, often because a flag is never set to true | Print or inspect the flag and confirm `setState` updates it |
| Callback runs when the screen builds | `onPressed: _submit()` calls the function instead of passing it | Pass `_submit` or `() => _submit()` |
| Button does not enable while typing | The flag changed without `setState` | Wrap the assignment in `setState` |
| Error about `setState` after dispose | An async task finished after the widget was removed | Check `mounted` before calling `setState` |
| Button stays disabled after a failed request | Reset code is only on the success path | Reset the flag in a `finally` block |
| Disabled button looks the same as enabled | A custom style hides the disabled colors | Handle the disabled state in the style (see the styling chapters) |
Disabled is not hidden or read-only
Disabling a button communicates "not available right now". It does not explain why. If a user cannot tell what is missing, a grey button is frustrating. Pair it with a hint, such as helper text under the field or a validation message. Also note that a disabled button is not a security measure. It controls the interface only, so any rule that matters, such as permissions or input limits, must be enforced again where the data is processed.
Disabled buttons are also skipped by keyboard focus traversal, so keyboard and screen reader users cannot reach them. This is correct for unavailable actions, but it means they cannot discover the button to learn why it is unavailable. Visible explanatory text solves that.
Summary of the working model
onPressednon-null means enabled.nullmeans disabled.- The widget's state decides which of the two to pass, and
setStateis what makes the button react. - Pass a function reference, not the result of calling it.
- The callback runs on a completed tap, not on pointer down.
- For asynchronous work, disable the button while it runs, reset it in
finally, and checkmounted. - Disabling the interface is not a replacement for validation elsewhere.
Exercise
A FilledButton is declared as FilledButton(onPressed: _save(), child: const Text('Save')), where _save is a method that returns void. The code does not compile. What is wrong, and how do you fix it so the button calls _save only when pressed and is disabled while a boolean field _busy is true?
Show answer
_save() calls the method during build and passes its result, which is void, where a VoidCallback? is expected. Pass a reference instead and use a conditional to produce null while busy: FilledButton(onPressed: _busy ? null : _save, child: const Text('Save')). Any change to _busy must happen inside setState so the button rebuilds.
Exercise
In the SaveButton example, what would happen if you removed the finally block and set _saving = false only after await widget.onSave() on the success path, and onSave threw an exception?
Show answer
The exception would skip the line that resets _saving, so the flag would stay true and onPressed would remain null. The button would stay disabled showing "Saving..." until the widget is rebuilt with fresh state. Resetting inside finally runs on both success and failure.