Sub topic 9
Submitting a Form: Validate, Save, and Reset
Assume you know basic Dart, nullable types, closures, StatefulWidget, setState, and layouts such as Column and Scaffold. This chapter focuses on what happens when a user submits a Form.
A Form groups related fields. Its FormState coordinates validation, saving, and resetting. A GlobalKey<FormState> gives your widget access to that state.
Validate before saving
Call validate() when the user submits the form. Flutter runs every field's validator and displays any returned error messages.
The method returns true only when every validator returns null. If validation fails, stop the submission and let the user correct the fields.
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>();
String _email = '';
void _submit() {
final form = _formKey.currentState!;
if (!form.validate()) {
return;
}
form.save();
debugPrint('Submitting $_email');
}
void _reset() {
_formKey.currentState!.reset();
// Reset values that live outside the Form as well.
setState(() {
_email = '';
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Sign up')),
body: Padding(
padding: const EdgeInsets.all(16),
child: Form(
key: _formKey,
child: Column(
children: [
TextFormField(
decoration: const InputDecoration(labelText: 'Email'),
keyboardType: TextInputType.emailAddress,
validator: (value) {
final text = value?.trim() ?? '';
if (text.isEmpty) return 'Email is required';
if (!text.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('Submit'),
),
const SizedBox(width: 8),
OutlinedButton(
onPressed: _reset,
child: const Text('Reset'),
),
],
),
],
),
),
),
);
}
}save() calls each field's onSaved callback. It does not run validation by itself, so call validate() first. The onSaved callback is a useful place to copy field values into a model or state variable.
Reset the form
reset() restores each field to its initial value and clears its validation state. For a field without an initial value, that usually means an empty field.
reset() does not undo changes made elsewhere in your application. If you copied a value into a separate variable, reset that variable too. If the value belongs to a controller, clear the controller separately.
The submission sequence
A server can still reject valid-looking input. Client validation improves feedback, but it does not replace server-side checks. Display a server error near the relevant field when possible, and show a general error for failures that do not belong to one field.
Exercise
Why should _submit call validate() before save()?
Show answer
validate() checks every field and returns false when any validator reports an error. Calling save() only after it returns true prevents invalid values from being submitted.