Sub topic 6
Grouping and hiding semantics
This chapter assumes you can build layouts in Flutter and know what the semantics tree is: the parallel tree of nodes that Flutter sends to TalkBack and VoiceOver. You should also have tried a screen reader once. Here you control how many nodes a screen reader sees and what each one says.
Why the default tree is sometimes too detailed
Flutter creates semantics nodes for widgets that carry meaning, such as Text, buttons and text fields. A composite UI element is often built from several of these. A rating row has an icon and a number. A product card has an image, a title, a price and a button.
A screen reader user moves through nodes one swipe at a time. If a card produces six nodes, they swipe six times and hear fragments like "star", then "4.5", then "stars". The visual design shows one idea, but the spoken interface shows several. Grouping fixes this. Hiding removes nodes that only add noise.
You have four tools:
| Tool | Effect |
|---|---|
| `MergeSemantics` | Combines all descendant nodes into one node |
| `Semantics(excludeSemantics: true)` | Sets your own label and drops everything beneath it |
| `ExcludeSemantics` | Removes the subtree from the semantics tree |
| `excludeFromSemantics` on `Image` | Removes a decorative image |
Merging with MergeSemantics
MergeSemantics takes the semantics of all its descendants and fuses them into a single node. Labels are concatenated, and actions and flags are combined.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: Scaffold(body: Center(child: RatingRow()))));
class RatingRow extends StatelessWidget {
const RatingRow({super.key});
@override
Widget build(BuildContext context) {
return MergeSemantics(
child: Row(
mainAxisSize: MainAxisSize.min,
children: const [
Icon(Icons.star),
Text('4.5 stars'),
],
),
);
}
}The Icon has no semanticLabel, so it adds nothing. The merged node reads "4.5 stars". If the icon had a semanticLabel: 'Rating', the merged label would contain both strings, separated by a newline, and the screen reader would read them in order.
Built-in merging
Many Material widgets already merge. ListTile, CheckboxListTile, SwitchListTile and Chip present one focusable item even though they contain several widgets. Do not wrap these again. Check the semantics before adding a wrapper.
The merge trap: competing actions
Merging combines actions, but a node can have only one tap action. If two descendants are both tappable, the merged node cannot expose both. Use MergeSemantics for purely informational groups, or for groups with a single interactive part. When a card has several separate buttons, leave them as separate nodes and merge only the text parts.
Card(
child: Column(
children: [
MergeSemantics(
child: Column(
children: [
Text(product.name),
Text('\$${product.price}'),
],
),
),
TextButton(onPressed: addToCart, child: const Text('Add to cart')),
],
),
)The name and price read as one item, and the button stays separate and focusable.
Replacing semantics with excludeSemantics
Sometimes the merged result is still wrong. A visual "4.5 ★★★★☆" might read awkwardly however you merge it. Set the label yourself and tell Flutter to ignore the children by passing excludeSemantics: true.
Semantics(
label: 'Rated 4.5 out of 5 stars',
excludeSemantics: true,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
for (var i = 0; i < 5; i++)
Icon(i < 4 ? Icons.star : Icons.star_border),
const SizedBox(width: 8),
const Text('4.5'),
],
),
)Without excludeSemantics, the label on the parent and the labels of the children would both remain. With it, the screen reader gets one node with exactly your wording.
This is the most reliable pattern for custom visuals such as star ratings, progress bars drawn with CustomPaint, and charts. Write the sentence a sighted user would infer from the picture.
Hiding with ExcludeSemantics
ExcludeSemantics removes its whole subtree from the semantics tree. The widgets still draw and still respond to touch, but assistive technology does not see them.
Stack(
children: [
const Positioned.fill(
child: ExcludeSemantics(
child: DecoratedBox(
decoration: BoxDecoration(color: Colors.black12),
),
),
),
const Text('Welcome back'),
],
)Its excluding property defaults to true. You can set it to a condition if the exclusion applies only in some states:
ExcludeSemantics(
excluding: _isLoading,
child: const ContentList(),
)Decorative images
For images, you do not need a wrapper. Use the properties on Image:
Image.asset(
'assets/team.png',
semanticLabel: 'Four teammates standing around a whiteboard',
)
Image.asset(
'assets/divider.png',
excludeFromSemantics: true,
)An informative image gets a description through semanticLabel. A purely decorative image, such as a divider, a background flourish or a picture that repeats adjacent text, gets excludeFromSemantics: true. An image with neither is silent when it has no label, but it can still become a stop in the swipe order in some setups. Make the choice explicit.
Deciding which tool to use
Ask these questions in order:
- Does the node carry no information, as with decoration or a repeated label? Exclude it.
- Do several nodes describe one idea and read well when joined? Use
MergeSemantics. - Does the joined text read badly, or is the visual drawn with custom painting? Use
Semanticswith alabelandexcludeSemantics: true. - Does the group contain several separate actions? Do not merge it. Merge only the passive parts.
Hiding what is not on screen
ExcludeSemantics is for content that is visible but should be silent. Content that is not visible should not be spoken either. Offstage, Visibility with maintainState only, and widgets scrolled out of a lazy list are handled by the framework. A common mistake is placing a widget behind another with Stack and Opacity, such as a loading overlay on top of a form. The form is still in the semantics tree, so a screen reader can reach it. Wrap it in ExcludeSemantics(excluding: _isLoading), or put the modal in a route, which blocks the content beneath it.
Inspecting the result
Do not guess what the tree looks like. Turn on the semantics debugger:
MaterialApp(
showSemanticsDebugger: true,
home: const HomePage(),
)The app draws a box and the label for every node. When you swipe in TalkBack or VoiceOver, you should see one box per idea. A card with six small boxes needs merging, and a box with a missing label needs a Semantics wrapper.
You can also check this in a widget test:
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('rating exposes one descriptive node', (tester) async {
final handle = tester.ensureSemantics();
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Semantics(
label: 'Rated 4.5 out of 5 stars',
excludeSemantics: true,
child: const Row(
children: [Icon(Icons.star), Text('4.5')],
),
),
),
),
);
expect(find.bySemanticsLabel('Rated 4.5 out of 5 stars'), findsOneWidget);
handle.dispose();
});
}ensureSemantics() is required because Flutter builds the semantics tree only when something asks for it.
Common errors
- Double reading. A parent
Semanticswith a label and children with their own labels, withoutexcludeSemantics. The screen reader reads both. - Lost buttons. A
MergeSemanticsthat wraps two tappable widgets. One of the two taps is lost. - Over-merging a whole screen. Wrapping a page in
MergeSemanticscreates one giant node. Group at the level of a single card, row or tile. - Hiding to silence a warning. Adding
excludeFromSemanticsto an informative image removes the information. Describe it instead. - Out-of-date labels. A hand-written label on a widget whose visible text changes. Build the label from the same data as the visible text.
Exercise
A product card contains an image of the product, a name, a price and an "Add to cart" button. Which parts should you merge, which should you leave separate, and what should you do with the image if the name already describes it?
Show answer
Merge the name and price with MergeSemantics so they read as one item. Leave the "Add to cart" button as its own node so it keeps its own tap action and can be focused and activated. If the name already describes the image, mark the image excludeFromSemantics: true so the screen reader does not repeat the same information. If the image shows something the text does not say, give it a semanticLabel instead.
Exercise
You wrap a Row containing two IconButtons in MergeSemantics to "tidy up" the swipe order. A TalkBack user reports that one of the buttons no longer works. Explain why, and give a fix.
Show answer
A merged node can expose only one tap action, so the actions of the two IconButtons conflict and one is lost. Remove the MergeSemantics so that each button is its own node, each with a tooltip as its label. If the two buttons must be grouped, use Semantics(container: true) without merging the actions, or merge only the passive text that sits beside them.