Flutter / Asynchronous application boundaries / Lesson 14
Focus node ownership and traversal
Own focus nodes for the right lifetime and verify keyboard traversal through a Flutter form.
On this page
Lesson goals
- Create and dispose an owned FocusNode.
- Explain focus traversal boundaries.
- Verify keyboard and accessibility behavior.
Define the focus contract
Focus identifies the control receiving keyboard input. A form should make the next action discoverable and preserve a sensible traversal order, including when validation fails. Most standard Flutter controls manage focus automatically. Create a FocusNode only when the feature needs explicit control, and identify the State object responsible for its lifetime before requesting focus programmatically.
Own and dispose a node
The stateful widget creates one node, attaches it to a text field and disposes it when the owner is removed. The button requests focus as a deliberate user action. Do not create a new node inside build or share one node between unrelated controls. This fragment needs a Flutter host and suitable constraints; it has not been run on a device.
import "package:flutter/material.dart";
class NoteField extends StatefulWidget {
const NoteField({super.key});
@override
State<NoteField> createState() => _NoteFieldState();
}
class _NoteFieldState extends State<NoteField> {
final focus = FocusNode(debugLabel: "note");
@override
void dispose() { focus.dispose(); super.dispose(); }
@override
Widget build(BuildContext context) => Column(children: [
TextField(focusNode: focus, decoration: const InputDecoration(labelText: "Note")),
TextButton(onPressed: focus.requestFocus, child: const Text("Focus note")),
]);
}
Activating Focus note requests focus for the Note field.
The State owns the node for its lifetime and releases it in dispose.
Group related controls
A FocusTraversalGroup can group fields for traversal while standard widgets manage their own nodes. This example does not claim a custom order or submit data. Test the actual platform and input method because keyboard, screen-reader focus and touch interaction have different behavior. Add validation and error handling at the owning form when the fields represent a real submission.
import "package:flutter/material.dart";
class FormFields extends StatelessWidget {
const FormFields({super.key});
@override
Widget build(BuildContext context) => const FocusTraversalGroup(
child: Column(children: [
TextField(decoration: InputDecoration(labelText: "Name")),
TextField(decoration: InputDecoration(labelText: "Email")),
]),
);
}
The form displays Name and Email fields.
The group contains two labeled standard text fields without manually allocating focus nodes.
Handle validation and scope
When validation fails, retain the draft, present an understandable error and move focus only when that helps the user complete the task. Ensure the target still exists before requesting focus after asynchronous work. A focus request does not validate input, authorize a server operation or guarantee that a screen reader announced an error. Keep those contracts separate.
Verify focus behavior
Use widget tests to check the intended focus transition and disposal, then exercise Tab and Shift-Tab on the target with an appropriate keyboard. Check screen-reader navigation, larger text and a hidden or removed field. Confirm the focus indicator remains visible and that removing the owner does not leave a listener or reference using a disposed node.
Common errors and fixes
Focus disappears after a rebuild.
- Why it happens
- A new FocusNode is created during each build.
- How to fix it
- Own one node in State and dispose it.
- Prevent it next time
- Test rebuilds while a field is focused.
Two fields compete for focus.
- Why it happens
- They share a node intended for one control.
- How to fix it
- Give each independently managed control its own node.
- Prevent it next time
- Document node ownership.
A focus request targets a removed field.
- Why it happens
- Asynchronous work completed after the owner was disposed.
- How to fix it
- Check the owning lifecycle before requesting focus.
- Prevent it next time
- Test delayed completion after navigation.
2 practice exercises
1. Why is FocusNode created in State rather than build?
Show worked solution
State gives it a stable lifetime across rebuilds and a disposal point. Allocating in build can lose focus and leak resources.
2. Does moving focus validate a form?
Show worked solution
No. Validate input and authorize the operation at their owners; focus is a separate interaction aid that helps users correct errors.
Key takeaways
- Own and dispose explicitly created focus nodes.
- Keep traversal and validation contracts distinct.
- Test actual keyboard and accessibility interaction.