Hit Testing and Repaint Optimization
Implement custom hit testing and shouldRepaint logic to keep painting performant.
Why Hit Testing and Repaint Matter
When you draw with CustomPainter you take full control of the canvas. But two costs are easy to overlook: hit testing (deciding which pixels respond to taps) and repainting (re-running your paint code every frame).
- A naive painter that always returns
truefromshouldRepaintrepaints on every rebuild, burning GPU and battery. - By default a custom-painted region is transparent to pointer events, so taps fall through to widgets behind it.
This lesson shows how to make custom drawings both interactive and efficient.
Anatomy of a CustomPainter
A CustomPainter exposes two key overrides: paint for drawing and shouldRepaint for deciding when to re-run paint. There is also an optional hitTest for pointer logic.
paint(Canvas canvas, Size size)— your drawing commands.shouldRepaint(covariant CustomPainter old)— returntrueonly when visual inputs changed.hitTest(Offset position)— returntrue/false/nullto control pointer routing.
class CirclePainter extends CustomPainter {
final Color color;
final double radius;
CirclePainter({required this.color, required this.radius});
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()..color = color;
canvas.drawCircle(size.center(Offset.zero), radius, paint);
}
@override
bool shouldRepaint(covariant CirclePainter old) =>
old.color != color || old.radius != radius;
}All lessons in this course
- The Canvas API: Paths, Paints, and Shaders
- Building an Interactive Custom Chart Widget
- Clipping, Blend Modes, and Layer Compositing
- Hit Testing and Repaint Optimization