Sub topic 13
Adding checkboxes and other inputs with FormField
This chapter assumes you can already build a Form with a GlobalKey<FormState> and write TextFormField validators that return an error string or null. It also assumes you are comfortable with nullable types and closures in Dart. Here you will apply the same validation, saving and resetting to inputs that are not text: checkboxes, ratings, and any widget you design yourself.
Why FormField exists
TextFormField is not special. It is a FormField<String> that happens to draw a TextField. When you call validate(), save() or reset() on a FormState, the form walks its descendants, finds every FormField, and calls the same method on each one.
A plain Checkbox is not a FormField, so the form never sees it. A required "I accept the terms" box would pass validation even when it is unchecked. Wrapping the checkbox in a FormField<bool> fixes that.
| Form method | What each registered field does |
|---|---|
| `validate()` | Runs its `validator` and stores the result in `errorText` |
| `save()` | Calls `onSaved` with the current value |
| `reset()` | Restores `initialValue` and clears the error |
The anatomy of FormField<T>
FormField<T> has one required argument, builder. The builder receives a FormFieldState<T>, which holds everything the field needs.
state.valueis the current value of typeT?.state.didChange(newValue)stores a new value, rebuilds the field, and validates it ifautovalidateModeasks for that.state.errorTextis the string from the last validation, ornull.state.hasErroristruewhenerrorTextis notnull.state.contextis the build context of the field, useful forTheme.of.
The other constructor arguments are the ones you know from TextFormField: initialValue, validator, onSaved, autovalidateMode and enabled.
A checkbox inline
The quickest approach is to build the field where you use it. The builder draws the checkbox and, because no InputDecorator is involved, you must draw the error text yourself.
FormField<bool>(
initialValue: false,
validator: (value) => value == true ? null : 'You must accept the terms',
builder: (state) => Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
CheckboxListTile(
value: state.value,
onChanged: state.didChange,
title: const Text('I accept the terms'),
),
if (state.hasError)
Text(
state.errorText!,
style: TextStyle(color: Theme.of(state.context).colorScheme.error),
),
],
),
)The checkbox reads its value from state.value and writes through state.didChange. It never stores the value in your own setState variable. That is what makes reset() work: the form restores the state object's value, and the checkbox follows.
Packaging a field as a reusable class
Inline fields get repetitive. Subclass FormField<T> and pass the builder to super. The result is a widget you can drop into any form with the usual validator and onSaved arguments.
import 'package:flutter/material.dart';
class CheckboxFormField extends FormField<bool> {
CheckboxFormField({
super.key,
required String title,
super.initialValue = false,
super.validator,
super.onSaved,
super.autovalidateMode,
ValueChanged<bool>? onChanged,
}) : super(
builder: (FormFieldState<bool> state) {
final theme = Theme.of(state.context);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
CheckboxListTile(
value: state.value ?? false,
onChanged: (checked) {
state.didChange(checked);
onChanged?.call(checked ?? false);
},
title: Text(title),
controlAffinity: ListTileControlAffinity.leading,
contentPadding: EdgeInsets.zero,
),
if (state.hasError)
Text(
state.errorText!,
style: theme.textTheme.bodySmall
?.copyWith(color: theme.colorScheme.error),
),
],
);
},
);
}The builder runs in the initializer list, so it cannot use this. It can use constructor parameters such as title and onChanged, and it receives the state as its argument.
A field that is not a standard widget
Any input that produces a value can become a form field. This star rating stores an int and is invalid until the user picks at least one star.
class RatingFormField extends FormField<int> {
RatingFormField({
super.key,
super.initialValue = 0,
super.validator,
super.onSaved,
super.autovalidateMode,
}) : super(
builder: (FormFieldState<int> state) {
final theme = Theme.of(state.context);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
for (var i = 1; i <= 5; i++)
IconButton(
tooltip: '$i star${i == 1 ? '' : 's'}',
icon: Icon(
i <= (state.value ?? 0)
? Icons.star
: Icons.star_border,
),
onPressed: () => state.didChange(i),
),
],
),
if (state.hasError)
Text(
state.errorText!,
style: theme.textTheme.bodySmall
?.copyWith(color: theme.colorScheme.error),
),
],
);
},
);
}Flutter also ships DropdownButtonFormField, which is a FormField around a dropdown. Use it instead of writing your own when a dropdown is what you need.
Using both fields in a form
This listing is complete and runs as shown. It combines the two fields above with a submit button and a reset button.
void main() => runApp(
const MaterialApp(
home: Scaffold(
body: Padding(padding: EdgeInsets.all(16), child: FeedbackForm()),
),
),
);
class FeedbackForm extends StatefulWidget {
const FeedbackForm({super.key});
@override
State<FeedbackForm> createState() => _FeedbackFormState();
}
class _FeedbackFormState extends State<FeedbackForm> {
final _formKey = GlobalKey<FormState>();
int _rating = 0;
bool _accepted = false;
void _submit() {
final form = _formKey.currentState!;
if (!form.validate()) return;
form.save();
debugPrint('rating=$_rating accepted=$_accepted');
}
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
RatingFormField(
validator: (value) =>
(value == null || value == 0) ? 'Pick a rating' : null,
onSaved: (value) => _rating = value ?? 0,
),
CheckboxFormField(
title: 'I accept the terms',
validator: (value) =>
value == true ? null : 'You must accept the terms',
onSaved: (value) => _accepted = value ?? false,
),
Row(
children: [
ElevatedButton(onPressed: _submit, child: const Text('Send')),
TextButton(
onPressed: () => _formKey.currentState!.reset(),
child: const Text('Reset'),
),
],
),
],
),
);
}
}Press Send with nothing selected and both error messages appear. Fix one field and press Send again, and only the remaining error is shown. Press Reset and both fields return to their initial values with no errors.
Common errors
- Keeping the value outside the state. If the checkbox reads a
boolfrom your ownStateclass,reset()clears the form's copy but not yours, so the screen and the form disagree. Read fromstate.valueand write withstate.didChange. - Forgetting to show the error.
validate()storeserrorText, but a custom field draws nothing unless the builder does. A form that never fails visibly is usually this bug. - Changing
initialValuelater. The field readsinitialValueonce, when its state is created. Passing a new value on a rebuild does not update it. Give the field a newKeyif it must restart. - Validating on first build. The default
AutovalidateMode.disabledwaits forvalidate(). PassAutovalidateMode.onUserInteractionif the checkbox should show its error right after the first tap, then untick.
Accessibility
A custom control needs the same care as a text field. Give icon buttons a tooltip, as the rating field does, so screen readers announce "3 stars" and not an unnamed button. Keep the error text next to the control so it is read in order. Do not rely on color alone, since the message text carries the meaning.
Exercise
A form contains a custom FormField<bool> for "Subscribe to newsletter". Pressing Reset empties every text field but leaves the subscribe checkbox ticked. The checkbox's value comes from a bool _subscribed variable in the surrounding State. What is wrong, and how do you fix it?
Show answer
The checkbox displays _subscribed, so the form's reset restores the field state's value but not the variable the widget reads. Make the builder use state.value, call state.didChange in onChanged, set initialValue to the starting value, and copy the result into _subscribed in onSaved.
Exercise
Write the validator for a FormField<int> rating that accepts only values from 3 to 5 and returns "Please rate at least 3 stars" otherwise, including when nothing is chosen.
Show answer
(value) => (value == null || value < 3) ? 'Please rate at least 3 stars' : null