Sub topic 5
Adding labels, roles and hints with Semantics
This chapter assumes you can write StatelessWidget and StatefulWidget classes and run an app on a device or emulator. It also assumes you have seen the semantics tree and have a screen reader (TalkBack or VoiceOver) available to try the results.
What the Semantics widget does
Flutter draws its own pixels, so Android and iOS cannot see your buttons or text. Flutter builds a semantics tree next to the render tree and sends that tree to the platform accessibility service. Standard widgets such as ElevatedButton, TextField and Switch add their own nodes. A custom widget built from GestureDetector, Container and Icon does not describe itself, so a screen reader may skip it or read it badly.
Semantics is the widget you use to describe a subtree yourself. It does not change layout or painting. It only adds or edits the information the platform receives.
A label, a role and a hint answer different questions
A screen reader announces three parts of a control, usually in this order: the name, the role, and the hint.
| Part | Question it answers | Semantics property | Example announcement |
|---|---|---|---|
| Label | What is this? | `label` | "Add to favorites" |
| Role | What kind of control is it? | `button`, `header`, `link`, `image`, `textField` | "button" |
| State or value | What is it right now? | `toggled`, `checked`, `selected`, `enabled`, `value` | "on" |
| Hint | What happens if I act on it? | `hint` | "Saves this item to your list" |
Each part has a job, and mixing them up causes most labeling mistakes.
Labels
A label is the name of the control. Keep it short and put the most important word first. Do not include the role, because the screen reader adds it. A label of "Favorite button" is read as "Favorite button, button".
Many built-in widgets take their label from something you already provide. ElevatedButton uses its child text. IconButton has no text, so it uses its tooltip as the label:
IconButton(
icon: const Icon(Icons.favorite_border),
tooltip: 'Add to favorites',
onPressed: _toggleFavorite,
)The tooltip also appears when a sighted user long-presses the button, so one string serves both audiences. An Icon on its own accepts a semanticLabel, and Image has the same property.
When you build a custom control, wrap it in Semantics and supply the label yourself:
Semantics(
button: true,
label: 'Add to favorites',
hint: 'Saves this item to your list',
child: GestureDetector(
onTap: _toggleFavorite,
child: const Icon(Icons.favorite_border),
),
)GestureDetector already registers a tap action with the semantics system. The button: true flag tells the screen reader to announce a button, and a double tap on a focused node calls onTap.
Roles
Flutter has no single "role" property. The role is the combination of flags you set. The most common ones are:
button: truefor something that can be activated.header: truefor a heading. Screen reader users jump between headings, so mark section titles.link: truefor navigation to another place.image: truefor a node that is a picture.textField: truefor editable text. Prefer a realTextField, which handles the many related properties for you.
Prefer a built-in widget over a flag when one exists. Switch, Checkbox and Slider add the role, the state, the value and the actions together.
State and value
State changes while the user works. Use the state properties instead of rewriting the label:
toggledfor on/off controls such as a switch.checkedfor checkbox-like controls, andselectedfor the current item in a set.enabled: falsefor controls that cannot be used right now.valuefor the current content, such as "50 percent" on a custom slider.
If the label changes from "Add to favorites" to "Remove from favorites", the user hears a different control name each time. A stable label with a changing state is easier to follow.
Hints
A hint describes the result of the action, not the control. Use it sparingly, because it adds time to every announcement. Many users turn hints off in their screen reader settings, so the label and state must make sense without them. Good hints are short and describe an outcome that is not obvious, such as "Opens the order history". Skip a hint when it only repeats the label.
A complete example
This app contains a custom favorite toggle with a stable label, a button role, an on/off state and a hint that follows the state:
import 'package:flutter/material.dart';
void main() {
runApp(
const MaterialApp(
home: Scaffold(body: Center(child: FavoriteToggle())),
),
);
}
class FavoriteToggle extends StatefulWidget {
const FavoriteToggle({super.key});
@override
State<FavoriteToggle> createState() => _FavoriteToggleState();
}
class _FavoriteToggleState extends State<FavoriteToggle> {
bool _favorite = false;
void _toggle() => setState(() => _favorite = !_favorite);
@override
Widget build(BuildContext context) {
return Semantics(
button: true,
toggled: _favorite,
label: 'Favorite',
hint: _favorite
? 'Removes this item from your list'
: 'Saves this item to your list',
child: GestureDetector(
onTap: _toggle,
child: Padding(
padding: const EdgeInsets.all(12),
child: Icon(
_favorite ? Icons.favorite : Icons.favorite_border,
size: 32,
),
),
),
);
}
}The padding gives the control a 56 by 56 logical pixel target, which is larger than the common 48 pixel minimum. The next chapters on tap targets cover that rule in detail.
How Semantics nodes combine
By default, a Semantics widget merges its information into the nearest ancestor node that can hold it. Two nested Semantics widgets can therefore produce one node, and that node reads as one item. Two properties change this behavior:
container: truemakes the widget start its own node and stops its data from merging upward.excludeSemantics: truedrops the semantics of all descendants and replaces them with the ones on this widget.
The second option is useful when you provide a complete description yourself. For example, a card with a title, a price and a decorative icon can become one node with the label "Blue lamp, 24 dollars". Do not use it to hide things that a user needs, because the children's own actions disappear too.
Common errors
- Labeling the wrong layer. A label on a parent merges with labels on children, so the user hears the text twice. Check the result on a device.
- Putting the role in the label. "Delete button" is read as "Delete button, button".
- Adding
Semanticsto a built-in widget that already has a label. ATextButtonwith text needs no wrapper. An extralabelcan override the visible text, which breaks voice control commands that use the words on screen. - Labels that differ from visible text. Users of voice control say what they see. Keep the semantic label equal to, or starting with, the visible text.
- Using
hintfor the name. Some screen readers skip hints, which leaves an unnamed control. - Forgetting the state. A custom toggle with no
toggledorcheckedflag looks the same to a screen reader whether it is on or off.
Checking your work
Set showSemanticsDebugger: true on MaterialApp to draw the semantics tree over your UI. Each node shows its label, so you can see missing and doubled labels without a screen reader. In widget tests, call tester.ensureSemantics() and then use find.bySemanticsLabel to confirm a node exists. Always finish with a real pass in TalkBack and VoiceOver, because they decide how the node sounds.
Exercise
A custom switch is built from a GestureDetector and an AnimatedContainer. You wrap it in Semantics with label: 'Notifications on' and change it to 'Notifications off' when the user taps it. Name two problems with this design and give a better one.
Show answer
First, the label changes with the state, so the control name changes every time and the user cannot tell the label from the state. Second, the Semantics has no toggled flag, so the platform has no on/off state, and the role may not be announced as a switch or button. A better design uses a stable label such as 'Notifications', sets button: true and toggled: isOn, and keeps hint short or empty. A built-in Switch with a label would handle all of this by itself.
Exercise
A product card shows an image, a title "Blue lamp", a price "$24" and a decorative divider. Describe how you would expose it as one item to a screen reader. Which property do you use on the card and on the divider?
Show answer
Wrap the card in Semantics with label: 'Blue lamp, 24 dollars' and excludeSemantics: true, so the children's separate nodes are replaced by one node. Mark the divider image with excludeFromSemantics: true, or let the card's excludeSemantics hide it. If the card is tappable, also keep an onTap action or a button role on the Semantics, because excluding descendants removes their actions.