Sub topic 14
Finding widgets by semantics
This chapter assumes you can write a basic testWidgets test, use find.text and find.byType, and know that pump rebuilds the tree. Here you will locate widgets by what a screen reader announces instead of by their type or text. You will also check accessibility rules in automated tests.
What the semantics tree is
Flutter builds a second tree next to the widget and render trees, called the semantics tree. Each node describes one thing a user can perceive or act on. A node can carry:
- a label, such as "Save"
- flags, such as "is a button" or "is enabled"
- actions, such as tap or scroll
Screen readers like TalkBack and VoiceOver read this tree. They never see your widgets.
Most built-in widgets create nodes for you. A Text contributes its string as a label. An ElevatedButton merges its child text into one button node. A custom widget built from GestureDetector and Icon has no meaningful node until you add one with the Semantics widget.
Testing through semantics gives you two benefits. A test that finds a widget by label fails when the label is missing, which is also the situation a screen-reader user would face. And the label is a stable name for the widget that does not depend on its type or position.
Turning semantics on in tests
The test environment does not build the semantics tree by default, because it costs time. Call tester.ensureSemantics() before you pump the widget. It returns a SemanticsHandle, and you must dispose of it when the test ends.
final handle = tester.ensureSemantics();
addTearDown(handle.dispose);addTearDown runs the callback even when an assertion fails, so semantics are always switched off again. If you forget ensureSemantics, find.bySemanticsLabel throws a StateError that tells you to call it.
Finding by label
find.bySemanticsLabel takes a String or a RegExp. A string must match the whole label. A regular expression matches if it finds a hit anywhere in the label.
The next example defines a toggle button that has no text. Its only identity is its semantic label, which changes with its state.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
class LikeButton extends StatefulWidget {
const LikeButton({super.key});
@override
State<LikeButton> createState() => _LikeButtonState();
}
class _LikeButtonState extends State<LikeButton> {
bool _liked = false;
@override
Widget build(BuildContext context) {
return Semantics(
container: true,
button: true,
label: _liked ? 'Unlike' : 'Like',
child: GestureDetector(
onTap: () => setState(() => _liked = !_liked),
child: Icon(_liked ? Icons.favorite : Icons.favorite_border),
),
);
}
}
void main() {
testWidgets('finds and taps the button by its label', (tester) async {
final handle = tester.ensureSemantics();
addTearDown(handle.dispose);
await tester.pumpWidget(
const MaterialApp(home: Scaffold(body: Center(child: LikeButton()))),
);
expect(find.bySemanticsLabel('Like'), findsOneWidget);
expect(find.bySemanticsLabel('Unlike'), findsNothing);
await tester.tap(find.bySemanticsLabel('Like'));
await tester.pump();
expect(find.bySemanticsLabel('Like'), findsNothing);
expect(find.bySemanticsLabel('Unlike'), findsOneWidget);
});
testWidgets('exposes button semantics', (tester) async {
final handle = tester.ensureSemantics();
addTearDown(handle.dispose);
await tester.pumpWidget(
const MaterialApp(home: Scaffold(body: Center(child: LikeButton()))),
);
final node = tester.getSemantics(find.bySemanticsLabel('Like'));
expect(node.label, 'Like');
expect(
node,
containsSemantics(label: 'Like', isButton: true, hasTapAction: true),
);
});
}Points to notice:
- The finder returns a normal
Finder. You can pass it totester.tap,expectandfindsOneWidgetlike any other. - The
pumpafter the tap matters. The semantics tree updates when a frame is built, so the label changes only afterpump. - With
container: true, theSemanticswidget owns its node. The childGestureDetectoradds its tap action to that same node.
Regular expressions
A RegExp helps when a label contains changing data.
expect(find.bySemanticsLabel(RegExp(r'^Item \d+$')), findsNWidgets(3));Anchor the pattern with ^ and $ when you want a whole-label match. Without anchors, RegExp('Like') also matches "Unlike", because the pattern is found inside the longer label.
Reading and matching a node
tester.getSemantics(finder) returns the SemanticsNode for the single widget the finder matches. It throws if the finder matches zero or several widgets. The node gives you label, value, hint, rect and getSemanticsData(). Use getSemanticsData().hasAction(SemanticsAction.tap) to ask about actions.
Two matchers compare a node against expected properties:
| Matcher | Checks | Use it when |
|---|---|---|
| `containsSemantics(...)` | Only the properties you pass | You care about a few properties, such as label and button flag |
| `matchesSemantics(...)` | Every property. Anything you omit must be false or empty | You want to pin down the whole node |
matchesSemantics is strict. A button that also reports "enabled" or "focusable" fails the match unless you list those flags. Start with containsSemantics, and switch to matchesSemantics only for widgets whose accessibility behavior is the point of the test.
Checking accessibility guidelines
Flutter ships guideline matchers that inspect the whole screen for common accessibility mistakes. You use them with meetsGuideline and expectLater.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('screen follows accessibility guidelines', (tester) async {
final handle = tester.ensureSemantics();
addTearDown(handle.dispose);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: const Center(child: Text('Counter')),
floatingActionButton: FloatingActionButton(
onPressed: () {},
tooltip: 'Increment',
child: const Icon(Icons.add),
),
),
),
);
await expectLater(tester, meetsGuideline(androidTapTargetGuideline));
await expectLater(tester, meetsGuideline(iOSTapTargetGuideline));
await expectLater(tester, meetsGuideline(labeledTapTargetGuideline));
await expectLater(tester, meetsGuideline(textContrastGuideline));
});
}| Guideline | What it enforces |
|---|---|
| `androidTapTargetGuideline` | Tappable areas at least 48 by 48 logical pixels |
| `iOSTapTargetGuideline` | Tappable areas at least 44 by 44 logical pixels |
| `labeledTapTargetGuideline` | Every tappable node has a label |
| `textContrastGuideline` | Text meets the minimum contrast ratio against its background |
Always await expectLater here. These guidelines are asynchronous. Without await, the test can finish before the check runs and report success for a failing screen.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `StateError` saying semantics are not enabled | `ensureSemantics` was not called before the finder | Call `tester.ensureSemantics()` at the start of the test |
| Finder returns `findsNothing` for text you can see | The label merged into a larger one, or the widget excludes semantics | Print the node label, or use a `RegExp` |
| `getSemantics` throws about multiple widgets | The label matches more than one node | Make the label unique, or narrow with `find.descendant` |
| Label did not change after a tap | No `pump` after the interaction | Add `await tester.pump()` |
| `matchesSemantics` fails on an extra flag | The matcher is strict | List the flag, or switch to `containsSemantics` |
| Later tests behave oddly | The handle was never disposed | Use `addTearDown(handle.dispose)` |
Choosing between finders
Use find.text or find.byType for plain checks of what is drawn. Use find.byKey when you need a stable test-only handle. Use find.bySemanticsLabel when a widget has no visible text, such as an icon button, or when you want the test to prove the widget is reachable by assistive technology. A test that finds a widget by label also fails when a developer removes that label, which is why this finder doubles as an accessibility check.
Exercise
Your test calls find.bySemanticsLabel('Like') and throws a StateError before any assertion runs. What is the most likely cause, and what is the fix?
Show answer
Semantics were never enabled for the test. Call final handle = tester.ensureSemantics(); before pumpWidget, and register addTearDown(handle.dispose) so semantics are switched off afterward.
Exercise
A screen has an icon-only button with no label. Which guideline matcher would catch this, and why must the call be written as await expectLater(tester, meetsGuideline(...)) instead of expect?
Show answer
labeledTapTargetGuideline fails for a tappable node that has no label. The guideline check is asynchronous. With expectLater, you await it, so the test waits for the result. With a plain expect, the test could end before the check finishes and miss the failure.