Sub topic 6
Grouping fields in a Form
Assume you know basic Dart syntax, nullable types, closures, StatefulWidget, setState, and layouts such as Column and Scaffold. This chapter uses those ideas to group related inputs and validate them together.
A Form is a widget that coordinates multiple form fields. Each TextFormField registers itself with the nearest Form. The Form can then validate, save, or reset all registered fields at once.
Create a form key
A GlobalKey<FormState> gives your code access to the form's state. The state provides methods such as:
validate()runs every field validator and returnstrueonly when all fields are valid.save()calls each field'sonSavedcallback.reset()restores the fields to their initial values and clears validation messages.
Keep the key in the state object so it remains stable while the widget rebuilds.
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: ProfileFormPage()));
}
class ProfileFormPage extends StatefulWidget {
const ProfileFormPage({super.key});
@override
State<ProfileFormPage> createState() => _ProfileFormPageState();
}
class _ProfileFormPageState extends State<ProfileFormPage> {
final _formKey = GlobalKey<FormState>();
String _name = '';
String _email = '';
void _submit() {
final form = _formKey.currentState!;
if (!form.validate()) {
return;
}
form.save();
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Saved $_name ($_email)')),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Profile')),
body: Padding(
padding: const EdgeInsets.all(16),
child: Form(
key: _formKey,
child: Column(
children: [
TextFormField(
decoration: const InputDecoration(labelText: 'Name'),
validator: (value) {
if (value == null || value.trim().isEmpty) {
return 'Enter your name';
}
return null;
},
onSaved: (value) => _name = value!.trim(),
),
TextFormField(
decoration: const InputDecoration(labelText: 'Email'),
keyboardType: TextInputType.emailAddress,
validator: (value) {
if (value == null || !value.contains('@')) {
return 'Enter a valid email address';
}
return null;
},
onSaved: (value) => _email = value!.trim(),
),
const SizedBox(height: 16),
Row(
children: [
ElevatedButton(
onPressed: _submit,
child: const Text('Save'),
),
const SizedBox(width: 8),
TextButton(
onPressed: () => _formKey.currentState!.reset(),
child: const Text('Reset'),
),
],
),
],
),
),
),
);
}
}The submit method validates before saving. This order matters. Invalid values must not be copied into the page's saved variables. A validator returns an error message when input is invalid and null when input is valid.
Common errors
- Calling
_formKey.currentState!.save()without first callingvalidate(). - Creating the
GlobalKeyinsidebuild, which gives the form a new key on every rebuild. - Forgetting to return
nullfrom a successful validator. - Calling
reset()on a different form key than the one assigned toForm.
Exercise
What does _formKey.currentState!.validate() return when one field's validator returns an error string?
Show answer
It returns false and displays the validation error for that field.