Sub topic 14
Controlling reading and traversal order
This chapter assumes you can build Flutter layouts, know StatelessWidget and StatefulWidget, and have used the Semantics widget from the earlier chapters. You should also have run an app with TalkBack or VoiceOver turned on.
Two orders, two systems
Flutter has two separate orderings, and they are easy to confuse:
| Row | Reading order | Focus traversal order |
|---|---|---|
| Used by | Screen readers (swipe next or previous) | Keyboard Tab and arrow keys, switch devices |
| Built from | The semantics tree | The focus tree |
| Controlled by | `Semantics.sortKey` | `FocusTraversalGroup`, `FocusTraversalOrder` |
| Default | Geometry: top to bottom, then by text direction | `ReadingOrderTraversalPolicy`, also geometric |
Changing one does not change the other. A screen reader user who swipes through a form follows the semantics order. A keyboard user who presses Tab follows the focus order. If you want both to be sensible, you configure both.
The default reading order
Flutter sorts sibling semantics nodes by their position on screen. In a left-to-right locale it reads top to bottom, and nodes at the same height go left to right. In a right-to-left locale, such as Arabic or Hebrew, the horizontal direction flips. This works because Flutter reads Directionality from the widget tree.
The order does not come from the order of children in your code. That matters most in two places:
StackandPositioned. A badge placed in the top-right corner is read before the title below it, even if you declared the badge last.- Rows with different heights. Nodes that overlap vertically are grouped into a line. Uneven heights can produce an order that looks odd on paper but is consistent with the geometry.
Most screens need no changes. You intervene when the visual layout and the logical order disagree.
Overriding reading order with sortKey
Semantics accepts a sortKey. The usual choice is OrdinalSortKey, which takes a number. Lower numbers are read first.
This example shows a product card with a "Sale" badge positioned above the title. By default a screen reader says "Sale" first. We want the title, then the price, then the badge.
import 'package:flutter/material.dart';
import 'package:flutter/semantics.dart';
void main() => runApp(
const MaterialApp(
showSemanticsDebugger: false,
home: Scaffold(body: Center(child: ProductCard())),
),
);
class ProductCard extends StatelessWidget {
const ProductCard({super.key});
@override
Widget build(BuildContext context) {
return SizedBox(
width: 280,
height: 140,
child: Stack(
children: [
Positioned(
top: 0,
right: 0,
child: Semantics(
sortKey: const OrdinalSortKey(2),
child: const Chip(label: Text('Sale')),
),
),
Positioned(
top: 40,
left: 0,
child: Semantics(
sortKey: const OrdinalSortKey(0),
child: const Text(
'Trail running shoes',
style: TextStyle(fontSize: 20),
),
),
),
Positioned(
top: 80,
left: 0,
child: Semantics(
sortKey: const OrdinalSortKey(1),
child: const Text('\$89.00'),
),
),
],
),
);
}
}Set showSemanticsDebugger: true on MaterialApp to draw the semantics tree over the UI. It shows which nodes exist, but you should still confirm the swipe order with a real screen reader.
Rules that prevent surprises
- Give a key to every sibling in the group. Nodes without a key are placed by geometry. Mixing keyed and unkeyed siblings makes the result hard to predict.
- Keys only compare with keys of the same type and name.
OrdinalSortKey(1)and a custom key class cannot be compared. Use one key type per group of siblings. - Use the
nameargument to separate groups.OrdinalSortKey(0, name: 'header')andOrdinalSortKey(0, name: 'body')are not compared directly. Flutter orders each named group on its own, so you can control one area of the screen without touching the rest. - Keys sort among siblings. The key decides order among nodes that share a parent in the semantics tree, not across the whole screen. If your sorted nodes end up in different branches, the order will not change as you expect. Wrapping the related widgets in a common
Semantics(container: true)or a shared parent is the fix.
Merging changes the order question
Reading order only matters between separate nodes. When you wrap a row in MergeSemantics, the screen reader sees one node, and its label is built from the children in their own traversal order. If the label reads in the wrong sequence ("stars 4.5" instead of "4.5 stars"), a sort key on the children fixes it. A clearer approach is to supply a single Semantics(label: '4.5 stars', excludeSemantics: true) and skip the problem.
Keyboard focus traversal
Keyboard users move through focusable widgets: buttons, text fields, and anything wrapped in Focus. The default policy is ReadingOrderTraversalPolicy, which also follows geometry. For many screens that is correct.
Suppose a two-column form lists Email and Password in the left column and Name and Phone in the right. Geometry would go Email, Name, Password, Phone. Users usually expect to finish a column first. Use FocusTraversalGroup with an ordered policy:
import 'package:flutter/material.dart';
class TwoColumnForm extends StatelessWidget {
const TwoColumnForm({super.key});
Widget _field(double order, String label) {
return FocusTraversalOrder(
order: NumericFocusOrder(order),
child: TextField(decoration: InputDecoration(labelText: label)),
);
}
@override
Widget build(BuildContext context) {
return FocusTraversalGroup(
policy: OrderedTraversalPolicy(),
child: Row(
children: [
Expanded(
child: Column(
children: [_field(1, 'Email'), _field(2, 'Password')],
),
),
Expanded(
child: Column(
children: [_field(3, 'Name'), _field(4, 'Phone')],
),
),
],
),
);
}
}The policy lives on the group, and each FocusTraversalOrder supplies a position inside it. Other options:
ReadingOrderTraversalPolicy: the default, geometric.OrderedTraversalPolicy: usesFocusTraversalOrder. Widgets without an order are visited after the ordered ones.WidgetOrderTraversalPolicy: follows the order in which widgets were built, which usually matches the order of children in code.LexicalFocusOrder('a'): a string key instead of a number, useful when the order is easier to name than to count.
Each FocusTraversalGroup forms its own scope. Tab moves through everything in one group before it moves to the next group. You can use this to keep a dialog or side panel together.
Common errors
- Sort keys on widgets that merge into a parent. If a child has its own key but is merged into a parent node, the key is ignored. Put the key on the node that actually appears in the tree.
- Using
sortKeyto fix focus order. It has no effect on Tab. UseFocusTraversalOrder. - Forgetting right-to-left layouts. A hard-coded geometric assumption breaks when
Directionalityflips. PreferOrdinalSortKeyorFocusTraversalOrder, which state the logic and work in both directions. - Hidden or offstage widgets. Excluded or offstage widgets do not appear in either order. Check that your numbering does not rely on a node that is sometimes missing. Gaps in numbers are fine, so leave room (0, 10, 20) for later insertions.
- Testing only with a keyboard or only with a screen reader. Each order needs its own check.
How to verify
Turn on TalkBack or VoiceOver and swipe right through the screen, listening for the sequence. For keyboard order, run the app on desktop or web, or connect a hardware keyboard to an emulator, and press Tab repeatedly while watching the focus highlight. In a widget test, tester.ensureSemantics() followed by tester.getSemantics(find.text('Sale')) lets you inspect individual nodes, but whether the whole sequence feels right is still a manual judgment.
Exercise
A screen has a Stack where a floating "Close" button is positioned at the top-left and the main article text fills the rest. TalkBack reads "Close" first, but you want the article read first and "Close" last. Which change fixes the screen reader order, and does it also change the order in which Tab visits the widgets?
Show answer
Wrap the article in Semantics(sortKey: OrdinalSortKey(0)) and the Close button in Semantics(sortKey: OrdinalSortKey(1)), so the sibling nodes sort with the article first. This does not change Tab order, because keyboard focus uses the focus tree. To change that, put both widgets in a FocusTraversalGroup(policy: OrderedTraversalPolicy()) and give each a FocusTraversalOrder with NumericFocusOrder values.
Exercise
You gave OrdinalSortKey(0) to one widget and left its two siblings without sort keys. The result is unpredictable. What should you do?
Show answer
Give every sibling in the group a sort key of the same type, for example 0, 1 and 2. Nodes without a key are ordered by geometry, so mixing keyed and unkeyed siblings makes the final order depend on layout.