Sub topic 10
Moving focus between fields
This chapter covers how focus moves from one field to the next, and how to send the user back to a field that failed validation. It assumes you can build a Form with TextFormField and validators, and that you know the State lifecycle (initState, dispose). Knowing GlobalKey<FormState> is enough. This chapter adds per-field keys.
What focus is
Only one field receives keystrokes at a time. Flutter calls that field the focused one. Each focusable widget owns a FocusNode, an object that tracks whether the widget has focus and lets you request or release it.
If you don't pass a focusNode to a TextField or TextFormField, the widget creates and disposes one internally. You only need your own node when your code must move focus to that specific field, or listen to its focus changes.
There are three ways to move focus:
| Goal | Tool |
|---|---|
| Go to the next field in reading order | `TextInputAction.next`, or `FocusScope.of(context).nextFocus()` |
| Go to a specific field | `focusNode.requestFocus()` |
| Leave all fields and close the keyboard | `FocusScope.of(context).unfocus()` or `focusNode.unfocus()` |
Letting the keyboard advance focus
Set textInputAction on a field to choose the action key shown on the soft keyboard. TextInputAction.next shows a "next" key. Pressing it moves focus to the next focusable widget in traversal order, with no code from you. TextInputAction.done closes the keyboard and unfocuses the field.
TextFormField(
textInputAction: TextInputAction.next,
decoration: const InputDecoration(labelText: 'Name'),
),
TextFormField(
textInputAction: TextInputAction.done,
decoration: const InputDecoration(labelText: 'Email'),
)These defaults come from the text editing machinery. When the action key is pressed and you haven't supplied onEditingComplete, the field moves focus for next and unfocuses for done. After that, it calls onFieldSubmitted. This lets you run your own code, such as submitting the form, in the last field's onFieldSubmitted without handling focus yourself.
On a multiline field the action key inserts a new line, so next and done do not apply unless you set keyboardType: TextInputType.text with maxLines greater than 1 and a different action. Avoid mixing them without testing on a device.
Traversal order
nextFocus() follows a traversal policy. The default is reading order: top to bottom, then left to right (or right to left in RTL locales). In a plain Column this matches the visual order, so you rarely need to configure it.
The default can be wrong when the layout puts fields in a different visual order than you want to tab through, for example a two-column layout. You can override it with a FocusTraversalGroup and explicit order numbers:
FocusTraversalGroup(
policy: OrderedTraversalPolicy(),
child: Row(
children: [
Expanded(
child: FocusTraversalOrder(
order: const NumericFocusOrder(2),
child: TextFormField(
decoration: const InputDecoration(labelText: 'Last name'),
),
),
),
Expanded(
child: FocusTraversalOrder(
order: const NumericFocusOrder(1),
child: TextFormField(
decoration: const InputDecoration(labelText: 'First name'),
),
),
),
],
),
)Here "First name" is focused before "Last name" even though it appears second in the Row. The same policy also governs the Tab key on desktop and web, so fixing the order helps keyboard users everywhere.
Owning FocusNodes
To move focus to a specific field, create a FocusNode in your State, pass it to the field, and dispose it. A FocusNode is a ChangeNotifier, so forgetting to dispose it leaks it, the same as a controller.
class _ExampleState extends State<Example> {
final _emailFocus = FocusNode();
@override
void dispose() {
_emailFocus.dispose();
super.dispose();
}
// ...
}Never create a FocusNode inside build. A new node on each rebuild loses the focus state and makes the field lose focus while the user types.
Focusing the first invalid field on submit
After a failed submit, the form shows error text, but the user may not see which field caused it. In a long form the invalid field can be off screen. A good pattern is to focus the first invalid field, which also scrolls it into view.
Form.validate() returns only a bool. To find out which field failed, give each field a GlobalKey<FormFieldState<String>> and read its hasError after validation.
The following program is complete and runnable. It uses next to move through the fields, submits from the last field's keyboard action, and focuses the first invalid field on failure.
import 'package:flutter/material.dart';
void main() => runApp(
const MaterialApp(
home: Scaffold(
body: Padding(
padding: EdgeInsets.all(16),
child: FocusDemoForm(),
),
),
),
);
class FocusDemoForm extends StatefulWidget {
const FocusDemoForm({super.key});
@override
State<FocusDemoForm> createState() => _FocusDemoFormState();
}
class _FocusDemoFormState extends State<FocusDemoForm> {
final _formKey = GlobalKey<FormState>();
final _nameKey = GlobalKey<FormFieldState<String>>();
final _emailKey = GlobalKey<FormFieldState<String>>();
final _passwordKey = GlobalKey<FormFieldState<String>>();
final _nameFocus = FocusNode();
final _emailFocus = FocusNode();
final _passwordFocus = FocusNode();
@override
void dispose() {
_nameFocus.dispose();
_emailFocus.dispose();
_passwordFocus.dispose();
super.dispose();
}
String? _required(String? value, String message) =>
(value == null || value.trim().isEmpty) ? message : null;
void _submit() {
final form = _formKey.currentState!;
if (form.validate()) {
FocusScope.of(context).unfocus();
debugPrint('Form is valid');
return;
}
final fields = [
(_nameKey, _nameFocus),
(_emailKey, _emailFocus),
(_passwordKey, _passwordFocus),
];
for (final (key, node) in fields) {
if (key.currentState?.hasError ?? false) {
node.requestFocus();
break;
}
}
}
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: SingleChildScrollView(
child: Column(
children: [
TextFormField(
key: _nameKey,
focusNode: _nameFocus,
autofocus: true,
textInputAction: TextInputAction.next,
decoration: const InputDecoration(labelText: 'Name'),
validator: (v) => _required(v, 'Name is required'),
),
TextFormField(
key: _emailKey,
focusNode: _emailFocus,
keyboardType: TextInputType.emailAddress,
textInputAction: TextInputAction.next,
decoration: const InputDecoration(labelText: 'Email'),
validator: (v) => (v ?? '').contains('@')
? null
: 'Enter a valid email address',
),
TextFormField(
key: _passwordKey,
focusNode: _passwordFocus,
obscureText: true,
textInputAction: TextInputAction.done,
decoration: const InputDecoration(labelText: 'Password'),
onFieldSubmitted: (_) => _submit(),
validator: (v) =>
(v ?? '').length < 8 ? 'Use at least 8 characters' : null,
),
const SizedBox(height: 16),
ElevatedButton(onPressed: _submit, child: const Text('Sign up')),
],
),
),
);
}
}The order of the fields list is your priority order, so keep it in the same order as the screen. When a field gains focus, its text editing widget scrolls itself into view, so the SingleChildScrollView lets the user see the invalid field.
Details and edge cases
autofocus: truefocuses a field when its route first appears. Use it on at most one field per screen. On a form that opens in a bottom sheet, it also raises the keyboard immediately, which can hide the layout.- Order of calls. The validation error shows when the field rebuilds after
validate(). CallingrequestFocus()right afterward in the same event handler is safe. Don't call it insidebuild, because that triggers focus changes during a build. - Using the
GlobalKeyon a field. Thekeyon aTextFormFieldis also howFormFieldStateis found. Don't share one key between two fields. - Tapping outside. The keyboard doesn't close when the user taps empty space. Wrap the screen in
GestureDetector(onTap: () => FocusScope.of(context).unfocus(), ...)if you want that. Addbehavior: HitTestBehavior.opaqueso taps on empty areas are caught. - Previous field.
FocusScope.of(context).previousFocus()moves backward. It is useful for a custom toolbar above the keyboard. - Don't validate on blur by accident. Listening to
focusNode.addListenerto validate when a field loses focus works, butAutovalidateMode.onUserInteractionalready covers the common case. Use a listener only for something that needs the focus event itself.
Common mistakes
- Creating
FocusNodeobjects inbuild, which resets focus on every rebuild. - Forgetting to dispose nodes.
- Setting
onEditingCompleteand then wondering whynextno longer advances. - Using
TextInputAction.nexton the last field, so the key does nothing useful. Usedone(orgo/sendfor a specific meaning). - Putting fields in a layout whose visual order differs from the tree order and relying on the default policy.
Exercise
A form has three fields: name, email and password. You press the keyboard's action key on the name field, but focus doesn't move to email. The name field has textInputAction: TextInputAction.next and an onEditingComplete: () => debugPrint('done'). What is wrong, and how do you fix it?
Show answer
Supplying onEditingComplete replaces the default behavior, which is where the "next" action calls nextFocus(). Either remove onEditingComplete and use onFieldSubmitted for any extra work, or call FocusScope.of(context).nextFocus() inside onEditingComplete.
Exercise
After a failed submit you want to focus the first invalid field. Form.validate() only returns a bool. What do you add to each field so you can find the invalid one, and what do you call on its focus node?
Show answer
Give each field a GlobalKey<FormFieldState<String>> as its key. After validate() returns false, check key.currentState?.hasError for each field in screen order and call requestFocus() on the FocusNode of the first one that has an error.