Sub topic 7
Validating with TextFormField
This chapter covers how TextFormField and Form check input. It assumes you can write Dart closures and nullable types, build a StatefulWidget with setState, and have already used TextField, TextEditingController and InputDecoration. The previous chapter showed how to wrap fields in a Form with a GlobalKey<FormState>. Here you connect that key to validators.
What TextFormField adds to TextField
TextFormField is a TextField wrapped in a FormField<String>. It accepts almost the same arguments (controller, decoration, keyboardType, obscureText, and so on). It also does three things a plain TextField cannot:
- It registers itself with the closest
Formabove it in the widget tree. - It accepts a
validator, a function that checks the current text. - It shows the validator's message through
InputDecoration.errorText, so you do not passerrorTextyourself.
A TextField outside a Form still works. It just cannot take part in form-wide validation.
The validator contract
A validator has the type String? Function(String? value). The rule is simple:
- Return
nullwhen the value is valid. - Return a non-null
Stringwhen it is invalid. Flutter shows that string as the error text.
The parameter is nullable because FormField is generic and a field's value can be null in general. With a TextFormField the text is normally an empty string rather than null, but handle both so the validator holds up if the field is used differently.
String? validateName(String? value) {
final text = value?.trim() ?? '';
if (text.isEmpty) return 'Name is required';
if (text.length < 2) return 'Name is too short';
return null;
}Check the cheapest and most basic rule first (empty), then more specific rules. Only one message can show per field, so the first failure wins.
How validate() works
FormState.validate() walks every FormField registered under that Form, calls each validator, stores the result in the field, and rebuilds the fields so the messages appear. It returns true only if all validators returned null.
Two details matter here:
validate()does not stop at the first invalid field. Every field is checked, so all errors appear at once.- It only checks fields that are currently mounted, meaning they exist in the widget tree.
A complete runnable example
This file runs as shown. It has two fields that use different validators, and the submit button reads the result of validate().
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>();
final _nameController = TextEditingController();
final _ageController = TextEditingController();
@override
void dispose() {
_nameController.dispose();
_ageController.dispose();
super.dispose();
}
String? _validateName(String? value) {
final text = value?.trim() ?? '';
if (text.isEmpty) return 'Name is required';
if (text.length < 2) return 'Name is too short';
return null;
}
String? _validateAge(String? value) {
final age = int.tryParse(value?.trim() ?? '');
if (age == null) return 'Enter a whole number';
if (age < 13 || age > 120) return 'Age must be between 13 and 120';
return null;
}
void _submit() {
final valid = _formKey.currentState?.validate() ?? false;
if (!valid) return;
debugPrint('Saving ${_nameController.text}, ${_ageController.text}');
}
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
children: [
TextFormField(
controller: _nameController,
decoration: const InputDecoration(labelText: 'Name'),
validator: _validateName,
),
TextFormField(
controller: _ageController,
keyboardType: TextInputType.number,
decoration: const InputDecoration(labelText: 'Age'),
validator: _validateAge,
),
const SizedBox(height: 16),
ElevatedButton(onPressed: _submit, child: const Text('Save')),
],
),
);
}
}Run it and press Save with both fields empty. Both error messages appear at once. Fix one field and press Save again. Only the remaining error shows, because validate() re-runs every validator and replaces the old results.
Note that _validateAge uses int.tryParse, which returns null for bad input instead of throwing. The keyboardType only picks the on-screen keyboard. A user can still paste letters, so the validator must reject them. Restricting what can be typed is the job of input formatters.
Rules for writing good validators
- Keep them pure and fast. A validator can run many times, including during rebuilds when automatic validation is on. Do not call a network or a database from it. Server checks belong after submission, covered in a later chapter.
- Do not call
setStateinside a validator. It runs during the build phase, andsetStatethere triggers a framework error. - Trim before checking emptiness. A field containing only spaces passes
value.isEmptybut is not meaningful input. - Write messages that say what to do. "Enter a valid email address" helps more than "Invalid".
- Do not validate optional fields as required. If a field may be blank, return
nullfor an empty value and only check the format when text is present.
String? validateOptionalPhone(String? value) {
final text = value?.trim() ?? '';
if (text.isEmpty) return null; // optional: blank is fine
if (!RegExp(r'^\+?[0-9 ]{7,15}$').hasMatch(text)) {
return 'Enter a valid phone number';
}
return null;
}Common errors and how to fix them
| Symptom | Cause | Fix |
|---|---|---|
| `Null check operator used on a null value` on `currentState!` | The key is not attached to a mounted `Form`, or the code runs before the first build | Pass the same key to `Form(key: ...)`. Use `currentState?.validate() ?? false` when in doubt. |
| Validators never run | Fields are not inside the `Form`, or the key belongs to another widget | Put the `TextFormField` below the `Form` in the tree and use one key per form. |
| Error "Duplicate GlobalKey" | The key was created inside `build()`, so each rebuild makes a new one | Create the key once as a field of the `State` class. |
| Assertion about `controller` and `initialValue` | Both were passed to the same `TextFormField` | Use only one. Put the starting text in the controller, for example `TextEditingController(text: 'Ada')`. |
| Field below the screen is never validated | A lazy `ListView` has not built that field, so it is not registered | Use a `SingleChildScrollView` with a `Column` for forms, or keep the field alive. |
| Layout jumps when an error appears | The error line adds height below the field | Reserve space with `helperText: ' '` in the `InputDecoration`. |
Empty-string errors
FormField treats any non-null error as invalid, including ''. That is occasionally useful: return '' to turn the border red without printing text, then explain the problem elsewhere, for example in a single summary above the form. Do not return '' by accident. A validator that ends with return '' instead of return null blocks submission with no visible reason.
Lazy lists and unmounted fields
Because only mounted fields are validated, a form that passes validate() can still contain invalid fields that were scrolled out of view and disposed. For short forms a Column inside a SingleChildScrollView keeps every field in the tree. For very long forms, validate your data model as well as the widgets.
Validating without a controller
A controller is optional when you only need validation. FormField keeps its own value, and onSaved (covered in the submission chapter) can copy it out. Use a controller when you need to read or change the text outside the form, for instance for cross-field checks or clearing a field.
Exercise
A form has a required "Nickname" field and an optional "Website" field. A user leaves both blank and presses Save. What should each validator return, and what does validate() return?
Show answer
The Nickname validator returns an error string such as 'Nickname is required', because blank is not allowed. The Website validator returns null for a blank value, because the field is optional. validate() returns false, since one validator returned a non-null value. Only the Nickname error is shown.
Exercise
This handler sometimes throws "Null check operator used on a null value". What is the likely cause, and how would you change the line so it cannot throw? void submit() { if (formKey.currentState!.validate()) { send(); } }
Show answer
currentState is null when the key is not attached to a mounted Form, for example if the Form was given a different key or was removed from the tree. Write if (_formKey.currentState?.validate() ?? false) { send(); }, and also confirm the same key is passed to Form(key: _formKey).
Exercise
Write a validator for a "Quantity" field that must be an integer from 1 to 99.
Show answer
String? validateQuantity(String? value) { final n = int.tryParse(value?.trim() ?? ''); if (n == null) return 'Enter a whole number'; if (n < 1 || n > 99) return 'Quantity must be between 1 and 99'; return null; }