Sub topic 14
Adding semantics to custom-painted widgets
A CustomPaint draws pixels, and a screen reader such as TalkBack on Android or VoiceOver on iOS cannot read pixels. This chapter shows how to describe a painted widget to assistive technology. It covers wrapping the widget in Semantics, giving individual painted regions their own nodes with semanticsBuilder, and checking the result.
It assumes you can write a CustomPainter with paint and shouldRepaint, and that you know what a widget's Size and Rect are. You do not need prior accessibility experience.
Why painted widgets are invisible by default
Flutter builds a separate semantics tree next to the render tree. Built-in widgets such as Text, Checkbox, and ElevatedButton add nodes to it. Each node can carry a label, a value, a bounding rectangle, and actions such as tap.
A CustomPaint adds no such nodes. Everything you draw with Canvas is invisible to a screen reader. This includes text drawn with TextPainter. A user with a screen reader would skip a progress ring, a chart, or a custom knob without knowing it exists.
You have three options:
- Wrap the whole
CustomPaintin aSemanticswidget, so it becomes one node. - Override
semanticsBuilderon the painter, so each painted region becomes its own node. - Mark the drawing as decorative so screen readers skip it.
Option 1: One node with the Semantics widget
If the drawing means one thing, such as a progress ring, wrap it in Semantics. Give it a label for what it is and a value for its current state.
import 'dart:math' as math;
import 'package:flutter/material.dart';
class RingPainter extends CustomPainter {
RingPainter({required this.progress});
final double progress; // 0.0 to 1.0
@override
void paint(Canvas canvas, Size size) {
final rect = (Offset.zero & size).deflate(6);
final track = Paint()
..color = Colors.grey.shade300
..style = PaintingStyle.stroke
..strokeWidth = 12;
final bar = Paint()
..color = Colors.blue
..style = PaintingStyle.stroke
..strokeWidth = 12
..strokeCap = StrokeCap.round;
canvas.drawArc(rect, 0, 2 * math.pi, false, track);
canvas.drawArc(rect, -math.pi / 2, 2 * math.pi * progress, false, bar);
}
@override
bool shouldRepaint(covariant RingPainter oldDelegate) =>
oldDelegate.progress != progress;
}
class AccessibleRing extends StatelessWidget {
const AccessibleRing({super.key, required this.progress});
final double progress;
@override
Widget build(BuildContext context) {
return Semantics(
label: 'Download progress',
value: '${(progress * 100).round()} percent',
child: CustomPaint(
size: const Size(120, 120),
painter: RingPainter(progress: progress),
),
);
}
}A screen reader now announces "Download progress, 40 percent". Because value is built from progress, the announcement changes whenever the widget rebuilds with a new number.
Use label for what the thing is and value for what it currently holds. Do not put the number in the label. If you do, the user hears a different label every time the progress changes, and the node looks like a new element.
Marking decoration
A background swirl or a divider flourish carries no information. Wrap it in ExcludeSemantics so a screen reader does not stop on it.
ExcludeSemantics(
child: CustomPaint(
size: const Size(double.infinity, 24),
painter: WavePainter(),
),
)This assumes a WavePainter like the one from the Path chapter.
Option 2: Several nodes with semanticsBuilder
A bar chart, a seat map, or a custom slider with several handles has parts. The user needs to move between those parts one at a time. One label on the whole chart cannot do that.
CustomPainter has a semanticsBuilder getter. It returns a function that takes the painter's Size and returns a list of CustomPainterSemantics. Each entry becomes one semantics node. These are the fields you use most:
| Field | Purpose |
|---|---|
| `rect` | The region of the canvas the node covers, in the painter's own coordinates. Screen readers use it for focus outlines and touch exploration. |
| `properties` | A `SemanticsProperties` with `label`, `value`, `onTap`, `sortKey`, `textDirection`, and similar fields. |
| `key` | A `Key` that lets Flutter match nodes across rebuilds instead of recreating them. |
| `transform` | An optional `Matrix4` applied to the rect. |
The example below paints a bar chart and exposes one node per bar. Both paint and semanticsBuilder use the same _slot helper, so the painted bars and the semantic regions stay aligned.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/semantics.dart';
class BarChartPainter extends CustomPainter {
BarChartPainter({required this.values, required this.labels})
: assert(values.length == labels.length);
final List<double> values; // each 0.0 to 1.0
final List<String> labels;
Rect _slot(int i, Size size) {
final width = size.width / values.length;
return Rect.fromLTWH(i * width, 0, width, size.height);
}
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()..color = Colors.teal;
for (var i = 0; i < values.length; i++) {
final slot = _slot(i, size);
final bar = Rect.fromLTRB(
slot.left + 4,
size.height - values[i] * size.height,
slot.right - 4,
size.height,
);
canvas.drawRect(bar, paint);
}
}
@override
SemanticsBuilderCallback get semanticsBuilder {
return (Size size) {
return [
for (var i = 0; i < values.length; i++)
CustomPainterSemantics(
key: ValueKey(i),
rect: _slot(i, size),
properties: SemanticsProperties(
label: labels[i],
value: '${(values[i] * 100).round()} percent',
textDirection: TextDirection.ltr,
sortKey: OrdinalSortKey(i.toDouble()),
),
),
];
};
}
@override
bool shouldRepaint(covariant BarChartPainter oldDelegate) =>
!listEquals(oldDelegate.values, values) ||
!listEquals(oldDelegate.labels, labels);
@override
bool shouldRebuildSemantics(covariant BarChartPainter oldDelegate) =>
shouldRepaint(oldDelegate);
}
class BarChart extends StatelessWidget {
const BarChart({super.key});
@override
Widget build(BuildContext context) {
return CustomPaint(
size: const Size(300, 160),
painter: BarChartPainter(
values: const [0.4, 0.8, 0.6],
labels: const ['Monday', 'Tuesday', 'Wednesday'],
),
);
}
}TalkBack or VoiceOver now reads "Monday, 40 percent", and a swipe moves to "Tuesday, 80 percent".
What each part does
semanticsBuilderis a getter. You override it to return a callback. It is not a method that takes aSize. This trips people up.rectuses canvas coordinates. The origin is the top-left of the painter's area, the same as inpaint. If you apply transforms inpaint, the semantics rect does not follow them automatically. Compute the final rectangle yourself or pass atransform.keykeeps nodes stable. With aValueKey, Flutter updates the existing node when a bar's value changes. Without keys, nodes are matched by position, which can make a screen reader lose its focus place after an update.sortKeyfixes reading order. By default, Flutter orders nodes by geometry, top to bottom and then left to right. That order is usually fine, but asortKeymakes it explicit when the layout is unusual.textDirectionis needed for labels. A node with a label but notextDirectioncan fail an assertion when the painter is not under aDirectionality-aware parent. Setting it is safe.
shouldRebuildSemantics
The framework calls shouldRebuildSemantics(oldDelegate) when the painter instance changes. It decides whether to call semanticsBuilder again. Its default implementation calls shouldRepaint, so you often do not need to override it.
Override it when the two answers differ. For example, a painter might repaint on every animation tick, but its semantic description only changes when the data does. Returning true from shouldRebuildSemantics on every frame forces the semantics tree to rebuild every frame, which is wasteful.
Handling actions
A node that accepts touch should also accept the matching accessibility action. If a bar responds to taps, add onTap to its SemanticsProperties:
properties: SemanticsProperties(
label: labels[i],
onTap: () => onBarSelected(i),
),onBarSelected here would be a callback passed into the painter. This is separate from hitTest on the painter, which controls pointer events. A screen reader user activates a node by double-tapping the focused element. That path goes through the semantics action, not through your GestureDetector. If you only handle pointer events, screen reader users cannot trigger the action. Wire both to the same function.
Common mistakes
- Putting values in labels. The label changes on every update, so the screen reader treats it as a different element. Keep labels stable and put changing data in
value. - Labeling both the wrapper and the nodes. If you wrap a painter that uses
semanticsBuilderin aSemanticswith a label, the user hears the label as a separate stop before the children. Use one approach, or make the wrapper a container withcontainer: trueand a short label. - Forgetting text drawn with
TextPainter. Painted text is not read aloud. Repeat the same text in a label. - Misaligned rects. If the semantic rect and the painted shape differ, touch exploration highlights the wrong area. Share one geometry helper, as
_slotdoes above. - Leaving decoration exposed. Unlabeled but focusable decoration makes the screen reader announce nothing and still stop there.
Checking your work
Run the app with the semantics debugger on. In MaterialApp, set showSemanticsDebugger: true. Flutter then draws each node's label and rectangle over the screen, so you can see missing nodes and misaligned rects without a screen reader.
After that, test with the real tools. Turn on TalkBack or VoiceOver, swipe through the widget, and listen to the order and wording. In widget tests, call tester.ensureSemantics() before pumpWidget so the semantics tree is built. Release the handle it returns when the test ends.
Exercise
A painter draws a volume knob. You wrap its CustomPaint in Semantics(label: 'Volume 70 percent') and then change the volume to 80. A screen reader user reports that the control seems like a different element each time. What is wrong, and how do you fix it?
Show answer
The changing number is in the label, so the label differs on every update. Make the label stable, for example Semantics(label: 'Volume', value: '80 percent', child: ...), so the screen reader announces the same element with a new value.
Exercise
A seat-map painter exposes one node per seat using semanticsBuilder, and tapping a seat works with a finger but not with TalkBack double-tap. What is missing, and where do you add it?
Show answer
The nodes have no semantic action. Add onTap to the SemanticsProperties of each CustomPainterSemantics, calling the same function the pointer handler uses. Pointer hit testing and semantic actions are separate paths.
Exercise
Your painter repaints every frame during an animation, but its bar labels and values never change. What should shouldRebuildSemantics return for those frames, and why?
Show answer
It should return false. The default calls shouldRepaint, which returns true each frame, so overriding it avoids rebuilding the semantics tree every frame when the description has not changed.