0Pricing
Flutter Mobile Development · Lesson

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 true from shouldRepaint repaints 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) — return true only when visual inputs changed.
  • hitTest(Offset position) — return true/false/null to 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

  1. The Canvas API: Paths, Paints, and Shaders
  2. Building an Interactive Custom Chart Widget
  3. Clipping, Blend Modes, and Layer Compositing
  4. Hit Testing and Repaint Optimization
← Back to Flutter Mobile Development