Sub topic 9
Submitting a Form: Validate, Save and Reset
This chapter covers the three methods on FormState that handle submission: validate(), save() and reset(). It assumes you know how to build a Form with a GlobalKey<FormState> and write a TextFormField validator that returns an error string or null. It also assumes you are comfortable with StatefulWidget, setState and async/await in Dart.
The Three Operations
A Form is a coordinator. It keeps a list of the FormField widgets below it (a TextFormField is one) and forwards calls to each of them. You reach the coordinator through _formKey.currentState, which is a FormState.
| Method | What it does on each field | Returns |
|---|---|---|
| `validate()` | Runs the field's `validator`, stores the result, and redraws the field with its error text | `true` if every validator returned `null` |
| `save()` | Calls the field's `onSaved` callback with the current value | nothing |
| `reset()` | Puts the field back to its `initialValue` and clears its error | nothing |
These are separate steps on purpose. Typing into a field never calls onSaved, so values are copied out of the form only when you ask for it.
validate()
validate() runs every validator in the form, not only until the first failure. All invalid fields show their error at once, so the user sees every problem in one pass.
The return value is what you branch on:
if (!_formKey.currentState!.validate()) {
return; // errors are already on screen
}Two details matter here:
- A field with no validator counts as valid. A
TextFormFieldwithout avalidatorreturnsnullimplicitly. - Calling
validate()turns on error display for fields whoseautovalidateModeisdisabled. The errors stay visible until the next validation. UnderAutovalidateMode.onUserInteraction, they update as the user edits.
save() and onSaved
save() calls each field's onSaved with the field's current value. Use it to move values out of the widgets and into your own variables or a model object.
TextFormField(
initialValue: 'Ada',
decoration: const InputDecoration(labelText: 'Name'),
validator: (value) =>
(value == null || value.trim().isEmpty) ? 'Name is required' : null,
onSaved: (value) => _name = value!.trim(),
)onSaved receives String?. After a successful validate() the value is non-null for a TextFormField, but the type still allows null. Handle it explicitly if your validator is permissive.
Always call save() after validate() returns true. save() does not validate, so calling it alone would copy invalid data into your model.
reset()
reset() restores each field's initialValue, clears its error text, and clears the "user has interacted" state. The next autovalidateMode: onUserInteraction cycle starts fresh.
Two rules for what "initial" means:
- A field built with
initialValue: 'Ada'returns to'Ada'. - A field with no
initialValuereturns to empty text.
TextFormField does not allow initialValue and controller together (a debug assertion fires). If you supply your own controller, reset() clears the text, because the controller carries no separate initial value. If you need a non-empty reset value with a controller, set controller.text yourself after calling reset().
Note that reset() does not touch the variables you filled in with onSaved. Those hold the last saved values until you overwrite them.
A Complete Example
The form below validates, saves, simulates a network call, and resets. It also guards against double submission and checks mounted after the await.
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 = '';
int? _age;
bool _submitting = false;
Future<void> _submit() async {
if (_submitting) return;
final form = _formKey.currentState!;
if (!form.validate()) return;
form.save();
setState(() => _submitting = true);
await Future<void>.delayed(const Duration(seconds: 1)); // fake API call
if (!mounted) return;
setState(() => _submitting = false);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Saved $_name, age $_age')),
);
form.reset();
}
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextFormField(
initialValue: 'Ada',
decoration: const InputDecoration(labelText: 'Name'),
textInputAction: TextInputAction.next,
validator: (value) => (value == null || value.trim().isEmpty)
? 'Name is required'
: null,
onSaved: (value) => _name = value!.trim(),
),
TextFormField(
decoration: const InputDecoration(labelText: 'Age'),
keyboardType: TextInputType.number,
textInputAction: TextInputAction.done,
onFieldSubmitted: (_) => _submit(),
validator: (value) {
final age = int.tryParse(value ?? '');
if (age == null) return 'Enter a whole number';
if (age < 0 || age > 120) return 'Enter an age from 0 to 120';
return null;
},
onSaved: (value) => _age = int.parse(value!),
),
const SizedBox(height: 16),
Row(
children: [
ElevatedButton(
onPressed: _submitting ? null : _submit,
child: Text(_submitting ? 'Saving...' : 'Save'),
),
const SizedBox(width: 8),
TextButton(
onPressed: _submitting ? null : _formKey.currentState?.reset,
child: const Text('Reset'),
),
],
),
],
),
);
}
}Walk through what happens on a tap of Save with the age field empty:
validate()runs both validators. The name passes. The age fails with "Enter a whole number".- The age error appears and
validate()returnsfalse. _submitreturns early.save()never runs, so_ageis stillnull.
With valid input, save() fills _name and _age, the fake request runs, and reset() brings back "Ada" and empties the age field.
The Reset button uses _formKey.currentState?.reset. On the first build the key has no state yet, so the expression evaluates to null, which would disable the button until the next rebuild. If that matters, use () => _formKey.currentState?.reset() instead.
Async Submission Details
Real submissions are asynchronous, which adds three concerns:
- Double taps. Disable the button, or return early with a flag like
_submitting, so one tap cannot start two requests. - Disposed widgets. If the user navigates away during the
await, theStateis gone. Checkmountedbefore callingsetStateor usingcontext. - When to reset. Reset after success, not before the request. If the call fails, the user still has their input and can retry.
Common Errors
Null check operator used on a null valueoncurrentState!. TheGlobalKeyis not attached to a mountedForm. This happens when the key is assigned to a different widget, or when you call it before the first build. Check thatkey: _formKeyis on theFormitself.- The same
GlobalKeyin two places. AGlobalKeymust be unique in the tree. Create one key per form, and keep it in aStateobject, not inbuild(), where it would be recreated on every rebuild and lose the form's state. - Values never arrive in your model. You forgot
save(), or you wroteonSavedon a widget that is not aFormField. A plainTextFieldignoresonSaved. - Saving invalid data.
save()called without checking thevalidate()result. - Fields that don't reset. A custom
FormFieldthat ignores itsinitialValuehas nothing to restore. PassinitialValueto theFormFieldconstructor.
Reading Values: onSaved or Controllers?
You have two ways to read what the user typed.
onSaved+save()reads values at one moment, on submit. It needs no controller and nodispose(). It fits plain forms where values are only needed on submit.- A
TextEditingControllergives live access to the text. It fits cross-field checks, formatting while typing, and programmatic edits. You must dispose it.
You can mix both in one form. Using onSaved for most fields and a controller only where you need it keeps the State class smaller.
Exercise
A user taps Submit with two invalid fields. Your handler is if (_formKey.currentState!.validate()) { _formKey.currentState!.save(); }. How many error messages appear, and is onSaved called on any field?
Show answer
Both error messages appear, because validate() runs every validator rather than stopping at the first failure. It returns false, so the if body is skipped and onSaved is not called on any field.
Exercise
A form uses TextFormField(controller: _email) with no initialValue. After a successful submit you call reset(). What is in the field afterward, and how would you make it show "[email protected]" instead?
Show answer
The field is empty, because a controller-backed field has no separate initial value to restore. Either drop the controller and pass initialValue: '[email protected]', or call reset() and then set _email.text = '[email protected]'. Passing both controller and initialValue fails a debug assertion.
Exercise
Why does the example check mounted after await Future.delayed(...), and what could go wrong without the check?
Show answer
The user may have left the screen during the await, which disposes the State. Calling setState or using context on a disposed State throws an error. Checking mounted and returning early avoids that.