Sub topic 15
Automated accessibility checks in widget tests
This chapter shows how to turn accessibility rules into widget tests that run on every commit. It assumes you can write basic Flutter widget tests with testWidgets and find. It also assumes you know what the semantics tree is and what the Semantics widget does, both covered in earlier chapters.
What automated tests can and cannot prove
Flutter's flutter_test package ships four accessibility guidelines. You run each one with meetsGuideline. They check measurable properties of the semantics tree and the rendered pixels.
| Guideline | What it checks | What it cannot tell you |
|---|---|---|
| `androidTapTargetGuideline` | Tappable nodes are at least 48 x 48 logical pixels | Whether neighbouring targets are too close together |
| `iOSTapTargetGuideline` | Tappable nodes are at least 44 x 44 logical pixels | Whether the target is easy to reach with one hand |
| `labeledTapTargetGuideline` | Every node with a tap or long-press action has a non-empty label | Whether the label is accurate or useful |
| `textContrastGuideline` | Text has a contrast ratio of at least 4.5:1, or 3:1 for large text | Contrast of text drawn over gradients or photos, or of icons |
A passing run means you have not regressed on these basics. It does not mean the screen is accessible. Reading order, hint wording, focus behaviour and how announcements sound still need a manual pass with TalkBack and VoiceOver.
Turning on semantics in a test
Flutter builds the semantics tree only when something asks for it, such as a screen reader. In a test nothing asks, so the tree is empty and label checks have nothing to inspect. Call tester.ensureSemantics() before pumping your widget. It returns a SemanticsHandle that you must dispose.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
class FavoriteButton extends StatelessWidget {
const FavoriteButton({super.key, required this.onPressed});
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
return Semantics(
button: true,
label: 'Add to favorites',
child: GestureDetector(
onTap: onPressed,
child: const SizedBox(
width: 48,
height: 48,
child: Center(child: Icon(Icons.favorite_border)),
),
),
);
}
}
void main() {
testWidgets('favorite button meets the basic guidelines', (tester) async {
final handle = tester.ensureSemantics();
addTearDown(handle.dispose);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Center(child: FavoriteButton(onPressed: () {})),
),
),
);
await expectLater(tester, meetsGuideline(androidTapTargetGuideline));
await expectLater(tester, meetsGuideline(iOSTapTargetGuideline));
await expectLater(tester, meetsGuideline(labeledTapTargetGuideline));
await expectLater(tester, meetsGuideline(textContrastGuideline));
});
}Register the disposal with addTearDown instead of calling handle.dispose() on the last line. If an expectation fails, the test stops early and a trailing dispose() never runs. The leaked handle can then affect later tests in the same file.
meetsGuideline is an async matcher, so use await expectLater(...). A plain expect will not wait for the contrast check, which has to capture the rendered image.
Reading a failure
Remove the SizedBox(width: 48, height: 48) wrapper and the Android and iOS checks fail. The failure message names the offending node and its size, for example a 24 x 24 icon. Remove the label and labeledTapTargetGuideline fails and points at a node with a tap action and no label. Treat each failure as a bug report on one widget.
Asserting on the semantics tree directly
The guidelines are generic. For rules specific to your app, inspect the tree yourself. Use find.bySemanticsLabel to locate a node by its label. Use tester.getSemantics to read the node's data.
testWidgets('favorite button is labeled and tappable', (tester) async {
final handle = tester.ensureSemantics();
addTearDown(handle.dispose);
await tester.pumpWidget(
MaterialApp(home: Scaffold(body: FavoriteButton(onPressed: () {}))),
);
expect(find.bySemanticsLabel('Add to favorites'), findsOneWidget);
final data = tester.getSemantics(find.byType(FavoriteButton)).getSemanticsData();
expect(data.label, 'Add to favorites');
expect(data.hasAction(SemanticsAction.tap), isTrue);
});Flutter also provides matchesSemantics, which compares a whole node. It is strict. Every flag you leave out is expected to be false, so a node from a standard widget such as IconButton needs several flags listed (enabled state, focusable and so on). Use it for small custom widgets. For larger ones, check only the properties you care about, as above.
When a test fails and you cannot see why, call debugDumpSemanticsTree() after pumpWidget. It prints every node with its label, actions and flags, in the order a screen reader would visit them.
Testing under different user settings
Real users run your app with large text, small screens and reduced motion. A widget test can simulate each of these through test values on the platform dispatcher and the view. Wrap them in a loop so one test body covers several configurations.
for (final scale in [1.0, 1.5, 2.0]) {
testWidgets('favorite button works at text scale $scale', (tester) async {
final handle = tester.ensureSemantics();
addTearDown(handle.dispose);
tester.view.physicalSize = const Size(360, 640);
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.reset);
tester.platformDispatcher.textScaleFactorTestValue = scale;
addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Column(
children: [
const Text('Your saved places'),
FavoriteButton(onPressed: () {}),
],
),
),
),
);
await expectLater(tester, meetsGuideline(androidTapTargetGuideline));
await expectLater(tester, meetsGuideline(labeledTapTargetGuideline));
});
}This test also catches layout overflow. When text grows and a Row or fixed-height container cannot hold it, Flutter throws a "RenderFlex overflowed" error during layout. The test framework reports that as a failure, so you do not need to assert anything extra.
The 360 x 640 size matters. The default test surface is 800 x 600 logical pixels, which hides overflow that appears on a phone.
Reduced motion
Set the accessibility features the same way. The widget below shortens its animation to zero when the user has asked for reduced motion.
class SavedNotice extends StatelessWidget {
const SavedNotice({super.key, required this.visible});
final bool visible;
@override
Widget build(BuildContext context) {
final reduceMotion = MediaQuery.disableAnimationsOf(context);
return AnimatedOpacity(
opacity: visible ? 1 : 0,
duration: reduceMotion ? Duration.zero : const Duration(milliseconds: 300),
child: const Text('Saved'),
);
}
}
void main() {
testWidgets('notice skips its animation when motion is reduced', (tester) async {
tester.platformDispatcher.accessibilityFeaturesTestValue =
const FakeAccessibilityFeatures(disableAnimations: true);
addTearDown(tester.platformDispatcher.clearAccessibilityFeaturesTestValue);
await tester.pumpWidget(
const MaterialApp(home: SavedNotice(visible: true)),
);
final opacity = tester.widget<AnimatedOpacity>(find.byType(AnimatedOpacity));
expect(opacity.duration, Duration.zero);
});
}FakeAccessibilityFeatures also supports boldText, highContrast and invertColors, so you can test those settings the same way.
Common errors
- Empty semantics tree. You forgot
ensureSemantics(). Label checks andfind.bySemanticsLabelthen fail or find nothing. - Tap target failures on
InkWellorGestureDetector. The guideline measures the semantics node, not the visible icon. Pad the tappable area, or useIconButton, which enforces a minimum size. - Test values leaking between tests. If you set
textScaleFactorTestValuewithout a teardown, later tests run at that scale. Register the clear call withaddTearDownright after setting the value. - Contrast failures you cannot reproduce by eye. The test measures pixels it rendered, so check the theme the test used. A bare
MaterialAppuses the default theme, not your app's theme. Pass your realThemeDatato the test. - False confidence from a passing run. The labeled-target guideline accepts the label
"button". Review label wording in code review or in a manual screen reader session.
Where this fits in your workflow
Run these tests in continuous integration alongside your other widget tests. They run without an emulator and take milliseconds each. Use them to guard against regressions, such as a designer shrinking a button or a developer adding an unlabeled icon button. Then use manual TalkBack and VoiceOver sessions to judge the things a test cannot judge: whether the screen makes sense when it is read aloud.
Exercise
A screen has a GestureDetector wrapping a 30 x 30 Icon with no Semantics widget. You run a test with tester.ensureSemantics() and check all four guidelines. Which guidelines fail, and what two changes make them pass?
Show answer
androidTapTargetGuideline and iOSTapTargetGuideline fail because the tappable node is 30 x 30, below 48 and 44. labeledTapTargetGuideline fails because the node has a tap action and no label. textContrastGuideline is unaffected because there is no text. Fix it by enlarging the tappable area to at least 48 x 48, for example with a SizedBox or padding inside the GestureDetector. Also wrap it in Semantics(button: true, label: '...') with a meaningful label.
Exercise
Why should you call addTearDown(handle.dispose) right after ensureSemantics() instead of calling handle.dispose() at the end of the test?
Show answer
If an expectLater call fails, the test body stops at that line and the final dispose() never runs. addTearDown runs the callback whether the test passes or fails, so the semantics handle is always released and later tests are not affected.