Sub topic 12
Making painted shapes respond to touch
A CustomPaint widget draws pixels, but it has no idea what those pixels mean. A circle you draw is not a button. This chapter shows how Flutter decides whether a touch landed on a painted shape, how to override that decision, and how to turn a touch into an action. It assumes you can write a CustomPainter with paint and shouldRepaint, and that you know how to wrap a widget in a GestureDetector.
How a touch reaches a painter
When you touch the screen, Flutter walks the render tree and asks each render object whether the touch position is inside it. This is called hit testing. CustomPaint creates a render object (RenderCustomPaint) that asks its painter for an answer.
The painter's hook is CustomPainter.hitTest(Offset position). It returns bool?:
truemeans the position hits the painter.falsemeans it misses.nullmeans "use the default".
The default depends on which painter you are asking:
| Painter slot | `hitTest` returns `null` | Effect |
|---|---|---|
| `painter` | treated as `true` | The whole rectangle is hit. |
| `foregroundPainter` | treated as `false` | The painter never captures touches. |
Two other facts matter. The rectangle must contain the touch first, because Flutter checks the widget's size before it calls your hitTest. Also, if the CustomPaint has a child, the child is tested before the painter.
The position you receive is in the local coordinates of the CustomPaint. The origin is its top-left corner, the same space paint starts in.
Limiting hits to the painted shape
The spine's DotPainter overrides hitTest so that only the circle responds. Here it is again with a color field, so you can see a visible reaction to taps:
import 'package:flutter/material.dart';
class DotPainter extends CustomPainter {
DotPainter({
required this.center,
required this.radius,
required this.color,
});
final Offset center;
final double radius;
final Color color;
@override
void paint(Canvas canvas, Size size) {
canvas.drawCircle(center, radius, Paint()..color = color);
}
@override
bool? hitTest(Offset position) => (position - center).distance <= radius;
@override
bool shouldRepaint(covariant DotPainter oldDelegate) =>
oldDelegate.center != center ||
oldDelegate.radius != radius ||
oldDelegate.color != color;
}position - center is an Offset, and .distance is its length. A point is inside a circle when its distance from the center is at most the radius. hitTest does not draw anything, so you can compute it in any way that matches what paint drew.
Reacting to the tap
hitTest only answers "is this mine?". To act on a touch, wrap the CustomPaint in a GestureDetector. The detector's default behavior, HitTestBehavior.deferToChild, relies on the child's hit test. Taps outside the circle then never reach the detector.
import 'package:flutter/material.dart';
class TappableDot extends StatefulWidget {
const TappableDot({super.key});
@override
State<TappableDot> createState() => _TappableDotState();
}
class _TappableDotState extends State<TappableDot> {
int _taps = 0;
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
GestureDetector(
onTap: () => setState(() => _taps++),
child: CustomPaint(
size: const Size(200, 200),
painter: DotPainter(
center: const Offset(100, 100),
radius: 40,
color: _taps.isEven ? Colors.red : Colors.green,
),
),
),
Text('Taps on the dot: $_taps'),
],
);
}
}Tapping the corner of the 200 by 200 box does nothing. Tapping the circle increments the counter and flips the color. Because color is part of shouldRepaint, the new color is painted.
Irregular shapes with Path.contains
Circles and rectangles have simple formulas. For anything else, build a Path and ask it. Path.contains(Offset) returns whether a point lies inside the filled path.
There is a catch. hitTest(Offset position) receives no Size, so a painter that builds its path from size cannot rebuild the path inside hitTest. You have three options:
- Build the path from fixed numbers, so no size is needed.
- Cache the path in
paint. This is fragile, becausehitTestcan run before the first paint. - Do the test in the gesture handler, where the widget knows its size.
The next example uses option 3. It shares one starPath function between painting and testing, so the two cannot drift apart.
import 'dart:math' as math;
import 'package:flutter/material.dart';
const Size kStarSize = Size(240, 240);
Path starPath(Size size) {
final c = size.center(Offset.zero);
final outer = size.shortestSide / 2;
final inner = outer * 0.4;
final path = Path();
for (var i = 0; i < 10; i++) {
final r = i.isEven ? outer : inner;
final a = -math.pi / 2 + i * math.pi / 5;
final p = Offset(c.dx + r * math.cos(a), c.dy + r * math.sin(a));
if (i == 0) {
path.moveTo(p.dx, p.dy);
} else {
path.lineTo(p.dx, p.dy);
}
}
return path..close();
}
class StarPainter extends CustomPainter {
StarPainter({required this.selected});
final bool selected;
@override
void paint(Canvas canvas, Size size) {
canvas.drawPath(
starPath(size),
Paint()..color = selected ? Colors.amber : Colors.grey,
);
}
@override
bool shouldRepaint(covariant StarPainter oldDelegate) =>
oldDelegate.selected != selected;
}
class StarButton extends StatefulWidget {
const StarButton({super.key});
@override
State<StarButton> createState() => _StarButtonState();
}
class _StarButtonState extends State<StarButton> {
bool _selected = false;
void _onTapDown(TapDownDetails details) {
if (starPath(kStarSize).contains(details.localPosition)) {
setState(() => _selected = !_selected);
}
}
@override
Widget build(BuildContext context) {
return GestureDetector(
behavior: HitTestBehavior.opaque,
onTapDown: _onTapDown,
child: CustomPaint(
size: kStarSize,
painter: StarPainter(selected: _selected),
),
);
}
}Here behavior: HitTestBehavior.opaque makes the whole rectangle deliver events to the detector. The handler then decides which taps count. details.localPosition is relative to the detector, which is the same size and position as the CustomPaint, so the coordinates match.
Choosing between several shapes
When shapes overlap, test them in the reverse of paint order, because the last shape painted is on top. Return the first match.
class Bubble {
const Bubble(this.center, this.radius);
final Offset center;
final double radius;
}
/// Returns the index of the topmost bubble under [point], or null.
int? topmostBubbleAt(List<Bubble> bubbles, Offset point) {
for (var i = bubbles.length - 1; i >= 0; i--) {
final b = bubbles[i];
if ((point - b.center).distance <= b.radius) return i;
}
return null;
}Call this from onTapDown with details.localPosition, store the returned index in state, and pass it to the painter so it can highlight that shape.
Edge cases and common errors
- Taps outside the shape still fire. The
painterslot treatsnullastrue. OverridehitTestto restrict it. AGestureDetectorwithHitTestBehavior.opaqueortranslucentwill also accept the whole rectangle regardless ofhitTest. - A
foregroundPainternever receives touches. Its default isfalse. Returntrueexplicitly if you need it to capture hits. - Touches pass through to widgets behind. Returning
falsefromhitTestlets widgets beneath theCustomPaintin aStackreceive the touch. This is often what you want for decorative layers. - Targets that are too small. Fingers are imprecise, and Material guidelines call for targets of at least 48 by 48 logical pixels. Add slop to the test, for example
<= radius + 12, without changing what is painted. - Wrong coordinates from global positions.
details.globalPositionis in screen space. UselocalPositionfor comparisons with your painted geometry. - Zero size. A
CustomPaintwith no child andSize.zerohas no area, so nothing can hit it. Give it a size, or put it under a parent with a size. - Hit-testing uses geometry, not pixels. A shape drawn with a stroke only is still "inside" under
Path.contains, becausecontainstests the fill area. For a stroke-only hit area, such as a thin line, test the distance to the line instead.
Hit testing answers touch questions only. Screen readers and keyboard users do not see your painted shapes at all. The accessibility chapter covers semanticsBuilder, which describes painted regions to assistive technology.
Exercise
You set foregroundPainter: DotPainter(...) on a CustomPaint, and the painter overrides nothing except paint. A GestureDetector with the default behavior wraps it. Why do taps on the circle do nothing, and what is the smallest change that fixes it?
Show answer
For foregroundPainter, a null result from hitTest is treated as false, so the painter never claims the touch and the detector, which defers to its child, sees no hit. The smallest fix is to override hitTest in the painter and return true for positions inside the circle (for example (position - center).distance <= radius). Moving the painter to the painter: slot also works, but then the whole rectangle is hit.
Exercise
Why is Path.contains hard to use directly inside CustomPainter.hitTest when the path depends on the widget size, and how does the star example work around it?
Show answer
hitTest receives only the touch Offset, not the Size, so the painter cannot rebuild a size-dependent path there. The star example uses a shared top-level starPath(Size) function and calls starPath(kStarSize).contains(details.localPosition) in the gesture handler, where the size is known. It sets HitTestBehavior.opaque so the detector receives every tap in the rectangle and filters them itself.