Sub topic 3
Moving focus between fields
This chapter assumes you know TextFormField, Form, GlobalKey<FormState>, validator functions, Dart closures, and nullable types.
Moving focus between fields
A FocusNode tracks whether a field has keyboard focus. Set textInputAction to control the keyboard's action key, and use onFieldSubmitted to move focus when the user presses it.
class _LoginFormState extends State<LoginForm> {
final _emailFocus = FocusNode();
final _passwordFocus = FocusNode();
@override
void dispose() {
_emailFocus.dispose();
_passwordFocus.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Column(children: [
TextFormField(
focusNode: _emailFocus,
textInputAction: TextInputAction.next,
onFieldSubmitted: (_) => _passwordFocus.requestFocus(),
decoration: const InputDecoration(labelText: 'Email'),
),
TextFormField(
focusNode: _passwordFocus,
obscureText: true,
textInputAction: TextInputAction.done,
onFieldSubmitted: (_) => FocusScope.of(context).unfocus(),
decoration: const InputDecoration(labelText: 'Password'),
),
]);
}
}Building reusable validators
A validator is a function that returns an error string or null. Factory functions produce validators you can reuse across fields.
typedef Validator = String? Function(String? value);
Validator required(String message) =>
(value) => (value == null || value.trim().isEmpty) ? message : null;
Validator minLength(int length) =>
(value) => (value ?? '').length < length
? 'Use at least $length characters'
: null;Validating fields against each other
A validator can read another field's controller. Validation runs when the form validates, so the comparison uses the latest text.
TextFormField(
controller: _confirm,
validator: (value) =>
value != _password.text ? 'Passwords do not match' : null,
),Adding checkboxes with FormField
FormField<bool> lets a checkbox take part in Form.validate().
FormField<bool>(
initialValue: false,
validator: (value) => value == true ? null : 'You must accept the terms',
builder: (state) => Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
CheckboxListTile(
value: state.value,
onChanged: state.didChange,
title: const Text('I accept the terms'),
),
if (state.hasError)
Text(state.errorText!,
style: TextStyle(color: Theme.of(state.context).colorScheme.error)),
],
),
)Showing server-side errors
The server cannot run in the validator, so store its error in state, then validate again to display it.
String? _serverError;
Future<void> _submit() async {
setState(() => _serverError = null);
if (!_formKey.currentState!.validate()) return;
final error = await api.register(_email.text); // returns String? on failure
setState(() => _serverError = error);
_formKey.currentState!.validate();
}Inside the email validator, return _serverError when it is set.
Testing a form with widget tests
A widget test taps the button, checks the message, then fixes the input and checks that the message is gone.
testWidgets('shows and clears the email error', (tester) async {
await tester.pumpWidget(
const MaterialApp(home: Scaffold(body: SignUpForm())),
);
await tester.tap(find.text('Sign up'));
await tester.pump();
expect(find.text('Email is required'), findsOneWidget);
await tester.enterText(find.byType(TextFormField), '[email protected]');
await tester.tap(find.text('Sign up'));
await tester.pump();
expect(find.text('Email is required'), findsNothing);
});Form usability and accessibility
- Use
labelTextso every field has a label that screen readers announce. - Write error messages that say what to fix.
- Do not rely on color alone to show an error.
- Set
autofillHints: [AutofillHints.email]so the operating system can fill the field.
> Not used.
Exercise
Why does the validator for the confirm field read _password.text at validation time rather than capturing its value when the widget is built?
Show answer
The validator runs each time the form validates. Reading the controller then compares against the text the user has entered most recently, so a later edit to the password is still checked.