Sub topic 13
Keyboard focus and navigation
This chapter assumes you can build Flutter layouts, write StatefulWidgets, and run an app on an emulator, desktop, or browser. It also assumes you know what the semantics tree is from earlier chapters. Here you will learn how keyboard focus works in Flutter, how to control the order in which the Tab key moves, and how to make custom widgets reachable and operable from the keyboard.
Why keyboard focus matters
Many people never use a touchscreen or mouse. Some use a physical keyboard because of a motor impairment. Others use a switch device or a screen reader that sends keyboard-style commands. Many sighted users simply prefer the keyboard on desktop and web. All of them depend on three things:
- A focus model: exactly one widget is the target of key presses at any moment.
- A predictable traversal order: Tab and Shift+Tab move focus forward and backward in a logical sequence.
- Activation: Enter or Space triggers the focused control.
Flutter provides all three. Standard Material and Cupertino widgets such as TextField, ElevatedButton, Checkbox, and Switch already take focus and respond to the keyboard. Problems appear when you build custom controls or when the visual layout does not match the order you want.
The focus tree
Flutter keeps a tree of FocusNode objects separate from the widget tree. A FocusNode holds the focus state of one widget. The node that currently receives key events is the primary focus. Its ancestors in the focus tree are said to have focus too, which lets a parent handle keys that a child ignores.
You rarely create nodes by hand for built-in widgets, because they create their own. You create them when you need to request focus, listen for focus changes, or build a custom control. Always dispose of nodes you own.
import 'package:flutter/material.dart';
class SearchBox extends StatefulWidget {
const SearchBox({super.key});
@override
State<SearchBox> createState() => _SearchBoxState();
}
class _SearchBoxState extends State<SearchBox> {
final FocusNode _focusNode = FocusNode(debugLabel: 'search');
@override
void dispose() {
_focusNode.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Column(
children: [
TextField(
focusNode: _focusNode,
decoration: const InputDecoration(labelText: 'Search'),
),
TextButton(
onPressed: _focusNode.requestFocus,
child: const Text('Jump to search'),
),
],
);
}
}Giving a node a debugLabel makes it easier to find in the Flutter DevTools widget inspector and in focus debugging output.
Default traversal order
When you press Tab, Flutter uses a traversal policy to choose the next focusable widget. The default is ReadingOrderTraversalPolicy. It sorts focusable widgets by their position: top to bottom, then left to right (or right to left in right-to-left locales). For most forms and screens this is already correct.
The default can fail in these cases:
- A
StackorPositionedlayout puts widgets in places that differ from your intended order. - A
Rowis reversed withtextDirectionorverticalDirection. - A screen has two columns, and you want to finish the left column before the right one.
In these cases, group widgets and choose an explicit policy.
Controlling the order with FocusTraversalGroup
FocusTraversalGroup creates a scope where one traversal policy applies. Inside it, FocusTraversalOrder assigns each widget a sortable value. With OrderedTraversalPolicy, the Tab key follows those values.
FocusTraversalGroup(
policy: OrderedTraversalPolicy(),
child: Column(
children: [
FocusTraversalOrder(
order: const NumericFocusOrder(1),
child: TextField(decoration: const InputDecoration(labelText: 'Email')),
),
FocusTraversalOrder(
order: const NumericFocusOrder(2),
child: TextField(decoration: const InputDecoration(labelText: 'Password')),
),
],
),
)Flutter offers three common policies:
| Policy | How it chooses the next widget | Typical use |
|---|---|---|
| `ReadingOrderTraversalPolicy` | Position on screen, in reading direction | Default for most screens |
| `OrderedTraversalPolicy` | Explicit `FocusTraversalOrder` values | Layouts that differ from reading order |
| `WidgetOrderTraversalPolicy` | Order of widgets in the widget tree | When tree order is the right order |
You can use LexicalFocusOrder('a') instead of numbers if you prefer string keys. Do not mix NumericFocusOrder and LexicalFocusOrder in the same group, because the policy cannot compare them.
Widgets inside an OrderedTraversalPolicy group that have no FocusTraversalOrder are visited after the ordered ones, so give every focusable widget in that group an order.
Use groups to keep a self-contained area, such as a dialog or a side panel, from interleaving with the rest of the page. Each group traverses its own children before focus leaves it.
Making custom widgets focusable
A GestureDetector is not focusable. Keyboard users cannot reach it, even if you add semantics for a screen reader. For custom controls, use FocusableActionDetector. It combines focus handling, keyboard shortcuts, actions, and hover detection in one widget.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class ToggleIntent extends Intent {
const ToggleIntent();
}
class FavoriteToggle extends StatefulWidget {
const FavoriteToggle({super.key});
@override
State<FavoriteToggle> createState() => _FavoriteToggleState();
}
class _FavoriteToggleState extends State<FavoriteToggle> {
bool _on = false;
bool _focused = false;
void _toggle() => setState(() => _on = !_on);
@override
Widget build(BuildContext context) {
return FocusableActionDetector(
onShowFocusHighlight: (value) => setState(() => _focused = value),
shortcuts: const {
SingleActivator(LogicalKeyboardKey.enter): ToggleIntent(),
SingleActivator(LogicalKeyboardKey.space): ToggleIntent(),
},
actions: {
ToggleIntent: CallbackAction<ToggleIntent>(
onInvoke: (intent) {
_toggle();
return null;
},
),
},
child: Semantics(
button: true,
toggled: _on,
label: 'Favorite',
child: GestureDetector(
onTap: _toggle,
child: Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
border: Border.all(
color: _focused ? Colors.blue : Colors.transparent,
width: 3,
),
),
child: Icon(_on ? Icons.favorite : Icons.favorite_border),
),
),
),
);
}
}This example shows the pattern. Three parts work together:
- Shortcuts map key presses to an
Intent, which describes what the user wants. - Actions map each
Intentto code that runs. - Focus highlight shows where focus is.
onShowFocusHighlightreportstrueonly when the user is navigating by keyboard, so mouse clicks do not draw the ring.
A visible focus indicator is required by WCAG 2.4.7 (Focus Visible). Never remove it without providing a replacement of equal clarity.
Prefer a built-in widget when one exists. InkWell takes focus and activates on Enter and Space by default, and IconButton does the same. Build on FocusableActionDetector only when no standard control fits.
Keyboard shortcuts for the whole screen
Shortcuts and Actions can be placed higher in the tree to define commands for an entire area, for example Ctrl+S to save.
Shortcuts(
shortcuts: const {
SingleActivator(LogicalKeyboardKey.keyS, control: true): SaveIntent(),
},
child: Actions(
actions: {
SaveIntent: CallbackAction<SaveIntent>(onInvoke: (_) => _save()),
},
child: const Focus(autofocus: true, child: EditorBody()),
),
)Shortcuts only fire when focus is inside the subtree. That is why the example places a Focus with autofocus: true inside it. Without any focused widget below the Shortcuts, the key press never reaches it.
Managing focus when the screen changes
Focus should move when the interface changes in a way the user needs to know about.
- Dialogs and bottom sheets. Flutter's
showDialogmoves focus into the dialog and traps it there until it closes, then returns focus to the previous widget. Do not undo this behavior. - Form errors. After a failed submit, call
requestFocus()on the first invalid field so the keyboard user lands on the problem. - Removed widgets. If the focused widget disappears, focus is lost. Move it to a sensible neighbor before removing it.
Use FocusScope to contain focus in a region you build yourself, such as a custom popup menu. ExcludeFocus removes a subtree from traversal, which suits content that is visually hidden but still in the tree. Setting canRequestFocus: false on a Focus or on a FocusNode has a similar effect for a single node. For content that is off screen, prefer removing it from the tree or wrapping it in Visibility with maintainState off, so users do not Tab into things they cannot see.
Common mistakes
- Using
GestureDetectorfor buttons. It has no focus and no keyboard activation. Use a button widget orFocusableActionDetector. - Hiding the focus ring. Custom themes sometimes set the focus color to transparent. Keep a visible indicator.
- Forgetting to dispose. A
FocusNodeyou create ininitStatemust be disposed, or it leaks. - Fixing order with
Positionedcoordinates. Tune traversal with groups and orders, not by moving widgets around. - Creating a keyboard trap. Focus must always be able to leave a component with Tab or Escape. Only modal dialogs may hold it, and only until closed.
Testing keyboard navigation
Test by hand first. On desktop or web, put the mouse aside and use only Tab, Shift+Tab, Enter, Space, and the arrow keys. Check that every control is reachable, the order makes sense, and the focus ring is always visible.
You can also automate a basic check. In a widget test, sendKeyEvent simulates a Tab press.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Tab moves from email to password', (tester) async {
final email = FocusNode();
final password = FocusNode();
addTearDown(email.dispose);
addTearDown(password.dispose);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Column(
children: [
TextField(focusNode: email, autofocus: true),
TextField(focusNode: password),
],
),
),
),
);
expect(email.hasPrimaryFocus, isTrue);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.pump();
expect(password.hasPrimaryFocus, isTrue);
});
}Exercise
A login screen has a Stack that places a "Forgot password?" link visually above the email field, but the link appears later in the widget tree. Pressing Tab visits the link last. You want the order to be link, email, password. Which widgets do you use, and what must you do for every focusable widget in the group?
Show answer
Wrap the form in a FocusTraversalGroup with an OrderedTraversalPolicy, and wrap each focusable widget in a FocusTraversalOrder with NumericFocusOrder values 1 (link), 2 (email), and 3 (password). Every focusable widget in the group needs an order, because widgets without one are visited after the ordered ones.
Exercise
Your custom star-rating control uses GestureDetector and works with taps. A keyboard user reports they cannot reach it with Tab. Name the cause and two ways to fix it.
Show answer
GestureDetector does not take focus or respond to keys. Fix it by replacing the control with a standard focusable widget such as InkWell or IconButton, or by wrapping it in FocusableActionDetector with Shortcuts for Enter and Space, an Action that performs the rating, and a visible focus highlight.