Sub topic 2
Restricting and shaping input with formatters
This chapter assumes you know Dart nullable types, StatefulWidget with setState, and Column layouts. You should already have a TextField with a TextEditingController.
Restricting and shaping input with formatters
An input formatter changes what a user can type. keyboardType only chooses which on-screen keyboard appears, so it does not block other characters. Pass formatters to inputFormatters to enforce the rules.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class ZipField extends StatelessWidget {
const ZipField({super.key});
@override
Widget build(BuildContext context) {
return TextFormField(
keyboardType: TextInputType.number,
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
LengthLimitingTextInputFormatter(5),
],
decoration: const InputDecoration(labelText: 'ZIP code'),
);
}
}Grouping fields in a Form
A Form widget wraps several fields. Create a GlobalKey<FormState> and pass it as the form's key. The key gives you a FormState that acts on every field inside the form.
| Method | What it does |
|---|---|
| `validate()` | Runs every validator and returns `true` if all pass |
| `save()` | Calls every field's `onSaved` callback |
| `reset()` | Restores initial values and clears error messages |
Validating with TextFormField
A validator has the type String? Function(String? value). It returns an error message to fail the field, or null to pass it.
String? validateZip(String? value) {
if (value == null || value.length != 5) return 'Enter 5 digits';
return null;
}Choosing when validation runs
autovalidateMode controls when errors appear. The default, AutovalidateMode.disabled, validates only when you call validate(). AutovalidateMode.onUserInteraction validates each field after the user edits it. AutovalidateMode.always validates on every rebuild.
flowchart TDSubmitting a form: validate, save and reset
Call validate() first. Only save and reset after it returns true.
final _formKey = GlobalKey<FormState>();
String _zip = '';
void _submit() {
if (_formKey.currentState!.validate()) {
_formKey.currentState!.save();
debugPrint('ZIP saved: $_zip');
_formKey.currentState!.reset();
}
}Exercise
A field has onSaved but the form never calls save(). What happens to the value, and why?
Show answer
The onSaved callback never runs, so the value is not stored. validate() only runs validators, and save() is the only call that triggers onSaved.