Sub topic 6
Grouping Fields in a Form
A TextField holds one piece of text. A Form groups several fields so you can validate, save, or reset them with one call. This chapter covers what Form does, how FormState tracks the fields inside it, and the mistakes that most often break it.
This chapter assumes you know Dart nullable types and closures, StatefulWidget with setState, and basic layouts such as Column and Scaffold. It also assumes you have used TextEditingController and InputDecoration.
What a Form does
Form is a container widget. It draws nothing, and it does not store values. It has two jobs:
- It creates a
FormStateobject that keeps a list of everyFormFieldbelow it in the widget tree. - It lets you call one method on that
FormStateto act on all of those fields at once.
A FormField<T> is the base widget for any input that takes part in a form. TextFormField is a FormField<String> that wraps a TextField. A plain TextField is not a FormField. Putting one inside a Form does nothing, because it never registers with the FormState.
Each FormField has its own FormFieldState, which holds the current value and the current error text. The Form only coordinates these states.
The three FormState operations
| Method | What it does | Returns |
|---|---|---|
| `validate()` | Runs every field's `validator` and shows or clears each field's error text | `true` if every field passed |
| `save()` | Calls every field's `onSaved` with the field's current value | nothing |
| `reset()` | Restores each field to its `initialValue` and clears its error text | nothing |
Two details matter in practice:
validate()runs the validator of every field. It does not stop at the first failure, so all invalid fields show their errors at once.save()does not validate. If you want to save only valid data, checkvalidate()first.
A complete form
This example uses a GlobalKey<FormState> to reach the FormState. It validates, saves, and resets. You can paste it into a new project's main.dart.
import 'package:flutter/material.dart';
void main() => runApp(
const MaterialApp(
home: Scaffold(
body: Padding(
padding: EdgeInsets.all(16),
child: ProfileForm(),
),
),
),
);
class ProfileForm extends StatefulWidget {
const ProfileForm({super.key});
@override
State<ProfileForm> createState() => _ProfileFormState();
}
class _ProfileFormState extends State<ProfileForm> {
final _formKey = GlobalKey<FormState>();
String _name = '';
String _city = '';
void _submit() {
final form = _formKey.currentState!;
if (!form.validate()) return;
form.save();
debugPrint('Saved $_name from $_city');
}
void _reset() => _formKey.currentState!.reset();
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
children: [
TextFormField(
decoration: const InputDecoration(labelText: 'Name'),
validator: (value) => (value == null || value.trim().isEmpty)
? 'Name is required'
: null,
onSaved: (value) => _name = (value ?? '').trim(),
),
TextFormField(
initialValue: 'Berlin',
decoration: const InputDecoration(labelText: 'City'),
validator: (value) => (value == null || value.trim().isEmpty)
? 'City is required'
: null,
onSaved: (value) => _city = (value ?? '').trim(),
),
const SizedBox(height: 16),
Row(
children: [
ElevatedButton(onPressed: _submit, child: const Text('Save')),
const SizedBox(width: 8),
OutlinedButton(onPressed: _reset, child: const Text('Reset')),
],
),
],
),
);
}
}Tapping Save with an empty name shows "Name is required" and leaves _name unchanged. Tapping Reset clears the name and puts "Berlin" back in the city field, because reset() returns each field to its initialValue.
The key is the link between your code and the form. _formKey.currentState is the FormState of the Form that was given that key. This is why the key must be created once and stored, as the next section explains.
Submission order
The usual sequence on a submit button is validate, then save, then use the data.
You can skip onSaved and read values from controllers instead. Both approaches work. onSaved keeps value-handling inside the form. Controllers are better when other code needs the text while the user is typing.
Reaching the FormState without a key
A GlobalKey is not the only way. Form.of(context) finds the nearest FormState above a given BuildContext. It is useful for a button widget that lives below the form.
import 'package:flutter/material.dart';
class SaveButton extends StatelessWidget {
const SaveButton({super.key, required this.onValid});
final VoidCallback onValid;
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () {
final form = Form.of(context);
if (form.validate()) {
form.save();
onValid();
}
},
child: const Text('Save'),
);
}
}Form.of throws if there is no Form above the context. Form.maybeOf returns null instead.
Common errors
Creating the key inside build
// Wrong: a new key on every rebuild
Widget build(BuildContext context) {
final formKey = GlobalKey<FormState>();
return Form(key: formKey, child: /* ... */);
}A new key on every rebuild makes Flutter treat the Form as a different widget and throw away its state, including entered text and error messages. Create the key as a field of your State class, as in ProfileForm.
currentState is null
_formKey.currentState is null when no mounted Form uses the key. That happens if you read it before the first build, after the widget is disposed, or if you forgot to pass key: _formKey. The ! operator then throws a null-check error. In a handler that only runs after a tap, the ! is safe once the key is attached.
Sharing one key between forms
A GlobalKey can belong to only one widget at a time. Using the same key on two forms that are on screen together causes a duplicate GlobalKey error. Give each form its own key.
Confusing the form key with a field key
The key on Form has type GlobalKey<FormState>. A field can have its own GlobalKey<FormFieldState<String>>. You rarely need a field key, but it lets you call didChange or validate on one field alone.
Lazy lists skip fields
validate() only reaches fields that are currently built. A ListView builds only the items near the screen, so a field scrolled far away is not mounted and is not validated. For forms of moderate size, use SingleChildScrollView with a Column, which builds every child.
Form(
key: _formKey,
child: SingleChildScrollView(
child: Column(
children: [
// every field here is built, so every field is validated
],
),
),
)Form-level options
Form has two options that affect all its fields:
autovalidateModesets the default validation timing for the whole form. The next chapter covers the choices. A mode set directly on a field applies to that field.onChangedis called whenever any field in the form changes. It is a good place to enable or disable a submit button or to mark the form as edited.
Form(
key: _formKey,
autovalidateMode: AutovalidateMode.onUserInteraction,
onChanged: () => setState(() => _edited = true),
child: /* fields */,
)This snippet assumes your State class declares bool _edited = false;. With a Form-level onUserInteraction setting, once the user has edited any field, the form can validate its other fields too, including ones the user has not touched yet. If you want each field to wait until the user edits it, set autovalidateMode on each field instead.
Quick checks
- The key is a field of the
Stateclass and is passed askey:toForm. - The fields are
TextFormFieldor anotherFormField, not plainTextField. - Submit calls
validate()first, thensave()or reads the controllers. - Any button that uses
Form.ofis below theFormin the tree. - Every field you want validated is built, so it is not off screen in a lazy list.
Exercise
A developer writes final key = GlobalKey<FormState>(); inside build, passes it to Form, and finds that typed text and error messages vanish whenever setState runs. What causes this, and what is the fix?
Show answer
Each rebuild creates a new GlobalKey, so Flutter sees a different widget identity for the Form and discards its FormState and all field states. Move the key into a final field of the State class so it is created once and reused across rebuilds.
Exercise
A form is built inside a ListView with 40 TextFormField children. The user taps Save with field 38 empty, but validate() returns true. Why, and how would you change the layout?
Show answer
ListView builds items lazily, so field 38 was never mounted and never registered with the FormState. validate() only checks registered fields. Use SingleChildScrollView with a Column so all fields are built and take part in validation.