Sub topic 16
Form usability and accessibility
This chapter assumes you can build a TextFormField with a validator, wrap fields in a Form, and use AutovalidateMode, TextInputAction and InputDecoration. It covers the choices that make a form easier to use for everyone, including people who rely on screen readers, large text, or a keyboard. Most of these choices take one or two lines of code. They are easy to skip, so the chapter also lists the common mistakes.
Why usability and accessibility belong together
A form fails when a user cannot tell what to type, cannot tell what went wrong, or cannot reach a control. Those are usability problems. For a person using TalkBack or VoiceOver, the same problems get worse, because the screen reader can only announce what the widget tree tells it.
Flutter builds a semantics tree next to the widget tree. Material widgets such as TextField add semantics for you: a label, a value, a "text field" role, and focus state. Your job is mostly to avoid breaking that information and to fill in the gaps.
The chapter follows the path of one user through a form.
Labels and hints
The most common usability mistake is using hintText as the only label. A hint disappears as soon as the user types, so a person who is interrupted cannot tell what the field was for. Screen readers also treat a label and a hint differently.
Use labelText for the field name. Use hintText for an example format, and helperText for a rule that applies before the user makes a mistake.
TextFormField(
keyboardType: TextInputType.phone,
decoration: const InputDecoration(
labelText: 'Phone number',
hintText: '555 010 1234',
helperText: 'We only call about your order',
prefixIcon: Icon(Icons.phone),
),
)With labelText set, Material floats the label above the text once the field has focus or content, so the name stays visible while typing. A screen reader announces the label when the field receives focus.
Icons need meaning, not decoration
A prefixIcon is decoration when the label already says the same thing. A suffixIcon that is a button, such as a "show password" toggle, is a control and must be labeled. IconButton takes a tooltip, and Flutter uses it as the accessible name.
class PasswordField extends StatefulWidget {
const PasswordField({super.key, required this.controller});
final TextEditingController controller;
@override
State<PasswordField> createState() => _PasswordFieldState();
}
class _PasswordFieldState extends State<PasswordField> {
bool _hidden = true;
@override
Widget build(BuildContext context) {
return TextFormField(
controller: widget.controller,
obscureText: _hidden,
autofillHints: const [AutofillHints.password],
decoration: InputDecoration(
labelText: 'Password',
suffixIcon: IconButton(
tooltip: _hidden ? 'Show password' : 'Hide password',
icon: Icon(_hidden ? Icons.visibility : Icons.visibility_off),
onPressed: () => setState(() => _hidden = !_hidden),
),
),
);
}
}Without the tooltip, a screen reader announces an unlabeled button, and the user cannot know what it does.
Keyboard and autofill choices
Typing is the slowest part of a mobile form, so reduce it.
- Set
keyboardTypeto match the data:emailAddress,phone,number,url. Remember that this only picks the keyboard. It does not restrict input, so you still need a validator or formatter. - Set
autofillHintsso the operating system can fill values from a password manager or saved contacts. Wrap related fields in anAutofillGroupso the system treats them as one form. - Set
textInputActionso the keyboard's action key does the right thing:nexton every field except the last,doneon the last. - Set
textCapitalizationfor names (TextCapitalization.words) and turn offautocorrectfor fields such as usernames and email addresses.
AutofillGroup(
child: Column(
children: [
TextFormField(
autofillHints: const [AutofillHints.email],
keyboardType: TextInputType.emailAddress,
textInputAction: TextInputAction.next,
autocorrect: false,
decoration: const InputDecoration(labelText: 'Email'),
),
TextFormField(
autofillHints: const [AutofillHints.name],
textCapitalization: TextCapitalization.words,
textInputAction: TextInputAction.done,
decoration: const InputDecoration(labelText: 'Full name'),
),
],
),
)Call TextInput.finishAutofillContext() after a successful submit if you want the platform to offer saving the credentials.
Error messages that help
A validator message is read aloud by screen readers when it appears, and it is the only explanation the user gets. Write messages that say what to do.
| Weak message | Better message |
|---|---|
| Invalid | Enter an email address like [email protected] |
| Error | Password must be at least 8 characters |
| Required | Enter your last name |
| Wrong format | Use the format MM/YY |
Rules that work well:
- Say what is wrong and how to fix it, in plain words.
- Do not rely on color. A red border alone does not help a user with color blindness, so the text must carry the meaning.
InputDecorationshowserrorTextbelow the field, and Material also adds an error icon only if you ask for one, so keep the text. - Keep messages short enough to wrap cleanly at large text sizes.
- Do not clear what the user typed when validation fails.
Validation timing
AutovalidateMode.always shows an error on an empty field before the user has typed anything, which feels like being scolded. AutovalidateMode.onUserInteraction validates a field after the user changes it, and is usually the best default. AutovalidateMode.disabled waits for validate(), which suits short forms where errors can wait until submit.
A useful hybrid is to stay quiet until the first failed submit, then switch to live validation so errors clear as the user fixes them.
class _CheckoutFormState extends State<CheckoutForm> {
final _formKey = GlobalKey<FormState>();
AutovalidateMode _mode = AutovalidateMode.disabled;
void _submit() {
if (_formKey.currentState!.validate()) {
_formKey.currentState!.save();
} else {
setState(() => _mode = AutovalidateMode.onUserInteraction);
}
}
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
autovalidateMode: _mode,
child: Column(
children: [
TextFormField(
decoration: const InputDecoration(labelText: 'Address'),
validator: (v) =>
(v == null || v.trim().isEmpty) ? 'Enter your address' : null,
),
FilledButton(onPressed: _submit, child: const Text('Place order')),
],
),
);
}
}
class CheckoutForm extends StatefulWidget {
const CheckoutForm({super.key});
@override
State<CheckoutForm> createState() => _CheckoutFormState();
}Focus after a failed submit
When validate() fails on a long form, the first invalid field may be off screen. The user sees nothing happen. Move focus to the first field with an error. One simple approach is to keep a FocusNode per field and check them in order.
final _nameFocus = FocusNode();
final _emailFocus = FocusNode();
bool _submitWithFocus() {
final form = _formKey.currentState!;
if (form.validate()) return true;
for (final node in [_nameFocus, _emailFocus]) {
// The field that failed keeps its error text; focus the first one.
final context = node.context;
if (context != null) {
final field = context.findAncestorStateOfType<FormFieldState<dynamic>>();
if (field != null && field.hasError) {
node.requestFocus();
break;
}
}
}
return false;
}Remember to dispose each FocusNode in dispose(). Requesting focus scrolls the field into view, and a screen reader then announces the field together with its error.
Targets, text size and keyboard users
- Keep tap targets at least 48 by 48 logical pixels. Material buttons and
IconButtonalready do this. Custom controls often do not. - Test with the system text size set to the largest value. Fixed-height containers around fields clip text. Prefer letting
InputDecorationsize itself, and put forms in aSingleChildScrollViewso the keyboard does not hide the submit button. - On desktop and web, users move with Tab and Shift+Tab. The default focus order follows the widget order, so do not reorder fields visually with
StackorPositionedin a way that breaks it. If you must, wrap the group inFocusTraversalGroupwith anOrderedTraversalPolicy. - Pressing Enter in the last field should submit. Use
onFieldSubmittedfor that.
Custom controls and semantics
Material fields come with semantics. A custom input, such as a GestureDetector wrapped around a rating row, does not. Add semantics yourself.
Semantics(
label: 'Rating',
value: '$rating of 5 stars',
increasedValue: '${(rating + 1).clamp(1, 5)} of 5 stars',
decreasedValue: '${(rating - 1).clamp(1, 5)} of 5 stars',
onIncrease: () => onChanged((rating + 1).clamp(1, 5)),
onDecrease: () => onChanged((rating - 1).clamp(1, 5)),
child: StarRow(rating: rating),
)Screen reader users can then swipe up or down to change the value. For a group of related inputs, such as a set of radio buttons, Semantics(container: true, label: ...) lets the reader announce the group name.
Use ExcludeSemantics only for purely decorative elements. Excluding a field's label or error text removes it for screen reader users.
Common mistakes
- Using
hintTextinstead oflabelText. - Unlabeled icon buttons inside
suffixIcon. - Showing an error only through color or a border.
AutovalidateMode.alwayson a fresh form.- Disabling the submit button with no explanation. Prefer an enabled button that validates and explains what is missing.
- Forgetting
textInputAction, so the user must tap each field to move on. - Setting
keyboardTypeand assuming input is restricted. - Not disposing controllers and focus nodes.
Checking your work
Flutter can check some accessibility rules in widget tests. The meetsGuideline matchers test tap target size, label presence and contrast.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('form meets basic accessibility guidelines', (tester) async {
final handle = tester.ensureSemantics();
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Column(
children: [
const TextField(decoration: InputDecoration(labelText: 'Email')),
ElevatedButton(onPressed: () {}, child: const Text('Sign up')),
],
),
),
),
);
await expectLater(tester, meetsGuideline(androidTapTargetGuideline));
await expectLater(tester, meetsGuideline(iOSTapTargetGuideline));
await expectLater(tester, meetsGuideline(labeledTapTargetGuideline));
await expectLater(tester, meetsGuideline(textContrastGuideline));
handle.dispose();
});
}These checks do not replace trying the form with TalkBack or VoiceOver. Turn the screen reader on, move through the form with swipes, and confirm that every field, button and error is announced with a meaningful name.
Exercise
A sign-up form uses hintText: 'Email' with no labelText, a suffixIcon: IconButton(icon: Icon(Icons.visibility)) on the password field, and shows errors by turning the border red with an empty errorText: ''. Name three changes that improve usability and accessibility.
Show answer
1) Replace the hint with labelText: 'Email' (keep a hint only for an example format), so the field name stays visible and is announced. 2) Add tooltip: 'Show password' (changing to 'Hide password' when visible) to the IconButton, so screen readers announce its purpose. 3) Return real validator messages such as 'Enter an email address like [email protected]', so the error is conveyed in text and not by color alone.
Exercise
You set keyboardType: TextInputType.number on a ZIP code field. A user pastes 12ab5. Does the field accept it, and what should you add?
Show answer
It accepts it, because keyboardType only chooses which keyboard is shown. Add inputFormatters: [FilteringTextInputFormatter.digitsOnly, LengthLimitingTextInputFormatter(5)] and a validator that checks the length, so pasted text is filtered and incomplete values produce a clear message.