Sub topic 7
Validating with TextFormField
This chapter assumes you know basic Dart, nullable types, closures, StatefulWidget, setState, and layouts such as Column and Scaffold. You will build a form that checks an email address before submission.
How a validator works
TextFormField is a TextField that connects to a Form. Its validator receives the field's current value and returns one of two results:
- An error message as a
Stringwhen the value is invalid. nullwhen the value is valid.
Flutter displays a returned error message below the field. The Form coordinates validation for all its descendant fields.
| Validator result | Meaning | What Flutter does |
|---|---|---|
| `'Email is required'` | The value is invalid | Shows the message below the field |
| `null` | The value is valid | Removes the validation error |
A GlobalKey<FormState> gives the widget that owns the form access to its FormState. Calling validate() runs every descendant validator and returns true only when all fields return null.
A complete validated form
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: SignUpPage()));
}
class SignUpPage extends StatefulWidget {
const SignUpPage({super.key});
@override
State<SignUpPage> createState() => _SignUpPageState();
}
class _SignUpPageState extends State<SignUpPage> {
final _formKey = GlobalKey<FormState>();
final _emailController = TextEditingController();
@override
void dispose() {
_emailController.dispose();
super.dispose();
}
String? _validateEmail(String? value) {
final email = value?.trim() ?? '';
if (email.isEmpty) {
return 'Email is required';
}
if (!email.contains('@')) {
return 'Enter a valid email address';
}
return null;
}
void _submit() {
final isValid = _formKey.currentState!.validate();
if (!isValid) {
return;
}
debugPrint('Submitting ${_emailController.text.trim()}');
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Create account')),
body: Padding(
padding: const EdgeInsets.all(16),
child: Form(
key: _formKey,
child: Column(
children: [
TextFormField(
controller: _emailController,
keyboardType: TextInputType.emailAddress,
decoration: const InputDecoration(
labelText: 'Email',
hintText: '[email protected]',
),
validator: _validateEmail,
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _submit,
child: const Text('Sign up'),
),
],
),
),
),
);
}
}The submit method validates before using the input. This prevents invalid data from reaching the next step. The controller is disposed because it owns resources outside the widget tree.
Choosing when validation runs
By default, validation runs when validate() is called. This is useful when you want to wait until submission.
You can also set autovalidateMode:
AutovalidateMode.disabledkeeps validation manual.AutovalidateMode.onUserInteractionvalidates after the user changes the field.AutovalidateMode.alwaysvalidates whenever the field rebuilds.
onUserInteraction usually gives useful feedback without showing errors before the user has touched the field.
Common errors
Do not use an empty string for a valid result. Return null. Also, do not forget the Form key: without the same key on the Form, _formKey.currentState cannot control that form.
A validator can receive null, so handle it before calling methods such as trim(). If you need the normalized value, trim it for validation and again when submitting.
Exercise
What should a validator return when the email contains a valid value, and what does _formKey.currentState!.validate() return when every field is valid?
Show answer
The validator should return null. The form's validate() method returns true.