Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 73 ยท Animation and graphics

CustomPaint and Canvas

Draw your own graphics in Flutter with CustomPaint and CustomPainter: Canvas calls, paths, gradients, clipping, shouldRepaint and a simple bar chart.

Widgets cover most screens, but sometimes you need a gauge, a chart, a signature pad or a game board. For that, Flutter gives you direct access to the same drawing API its own widgets use: the Canvas. You describe shapes and colors, and the engine paints them.

You use it through two classes: CustomPaint, a widget that takes up space in the tree, and CustomPainter, an object with a paint(Canvas, Size) method. This lesson covers the canvas calls you need most, how to keep painting fast with shouldRepaint, and builds a bar chart.

Real vs stand-in. The Dart code is real Flutter and read-only. The live examples use the browser's 2D canvas, whose API is very close (fillRect, paths, gradients, clip, save and restore), so you can practice the ideas here. Names differ: Flutter's Paint object replaces the canvas fill/stroke state.

Three pieces

CustomPaint The widget that reserves space.
CustomPainter Holds paint() and shouldRepaint().
Canvas and Paint Draw calls and their style.
1 / 2

Your first painter

DART
class CirclePainter extends CustomPainter {
  const CirclePainter({required this.color});
  final Color color;

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = color
      ..style = PaintingStyle.fill;
    final center = Offset(size.width / 2, size.height / 2);
    final radius = size.shortestSide / 2 - 8;
    canvas.drawCircle(center, radius, paint);
  }

  @override
  bool shouldRepaint(CirclePainter oldDelegate) => oldDelegate.color != color;
}

// In a build method:
CustomPaint(
  size: const Size(200, 200),
  painter: CirclePainter(color: Colors.teal),
)

Three facts to remember:

  1. The coordinate system starts at the top-left: x grows to the right, y grows down.
  2. size is what the layout gave you. With a child, the CustomPaint takes the child's size; without one, it uses size (or zero if you gave none, so a painter in an unconstrained spot seems to vanish). Layout rules are covered in Constraints go down, sizes go up.
  3. paint runs again whenever the object needs repainting. Never create long-lived state there.

Paint, shapes and text

A Paint holds the color, the style (fill or stroke), strokeWidth, strokeCap, a shader for gradients, and more. Common canvas calls:

Call Draws
drawRect(rect, paint) / drawRRect Rectangle / rounded rectangle
drawCircle(center, radius, paint) Circle
drawLine(p1, p2, paint) Line
drawArc(rect, start, sweep, useCenter, paint) Arc or pie slice (angles in radians)
drawPath(path, paint) Any shape you built with Path
drawParagraph / TextPainter Text

Text is drawn with a TextPainter, which must be laid out before painting:

DART
final tp = TextPainter(
  text: const TextSpan(text: '42%', style: TextStyle(fontSize: 24, color: Colors.black)),
  textDirection: TextDirection.ltr,
)..layout();
tp.paint(canvas, Offset(size.width / 2 - tp.width / 2, size.height / 2 - tp.height / 2));

Paths

A Path is a list of drawing instructions: move the pen, draw lines, curves and arcs, then close.

DART
final path = Path()
  ..moveTo(0, size.height)
  ..lineTo(size.width * 0.3, size.height * 0.4)
  ..quadraticBezierTo(size.width * 0.5, 0, size.width * 0.7, size.height * 0.5)
  ..lineTo(size.width, size.height)
  ..close();
canvas.drawPath(path, Paint()..color = Colors.indigo);

quadraticBezierTo takes one control point and an end point; cubicTo takes two control points. Combine shapes with Path.combine(PathOperation.union, a, b) and test points with path.contains(offset), which is handy for hit testing.

Gradients

A gradient is a shader attached to a Paint. It needs the rectangle it spans so that the colors line up with your shape:

DART
final rect = Offset.zero & size;
final paint = Paint()
  ..shader = const LinearGradient(
    begin: Alignment.topCenter,
    end: Alignment.bottomCenter,
    colors: [Color(0xFF7C4DFF), Color(0xFF00BFA5)],
  ).createShader(rect);
canvas.drawRRect(RRect.fromRectAndRadius(rect, const Radius.circular(16)), paint);

RadialGradient and SweepGradient work the same way.

Saving, transforming and clipping

The canvas carries state: a transform (translate, rotate, scale) and a clip. save() stores that state and restore() returns to it, so you can draw something rotated without changing everything after it.

DART
canvas.save();
canvas.translate(size.width / 2, size.height / 2);   // new origin: the center
canvas.rotate(math.pi / 6);                           // 30 degrees
canvas.drawRect(const Rect.fromLTWH(-40, -10, 80, 20), paint);
canvas.restore();                                     // back to normal

canvas.clipRect, clipRRect and clipPath limit later drawing to a region. Everything outside is cut off. Always wrap clipped drawing in save/restore, otherwise the clip stays for the rest of paint.

Try the ideas on a browser canvas

Stand-in: paths, gradient, transform and clip

Only the orange bar is tilted, because restore() undid the rotation. If you remove the save and restore around clip, everything drawn afterwards would be cut to the circle: the same trap exists in Flutter.

shouldRepaint

CustomPaint repaints when its widget is rebuilt with a new painter and shouldRepaint(oldDelegate) returns true. If it returns false, Flutter reuses the previous picture. Compare exactly the fields you draw from:

DART
@override
bool shouldRepaint(BarChartPainter old) => !listEquals(old.values, values) || old.barColor != barColor;

Returning true always is safe but wasteful; returning false wrongly leaves stale pixels on screen. For animation, give the painter a repaint listenable instead of rebuilding widgets: super(repaint: animation) makes the canvas repaint on every tick without rebuilding the tree (see Explicit animations).

When a CustomPaint animates while its neighbors stay still, wrap it in a RepaintBoundary so only its layer repaints.

A simple bar chart

The scaling step is plain arithmetic: map a value from the data range onto pixels. Because pixel y grows downward, the bar's top is height - value * scale.

DART
class BarChartPainter extends CustomPainter {
  BarChartPainter({required this.values, this.barColor = const Color(0xFF3F51B5)});
  final List<double> values;
  final Color barColor;

  @override
  void paint(Canvas canvas, Size size) {
    if (values.isEmpty) return;
    final maxValue = values.reduce(math.max);
    final slot = size.width / values.length;
    final barWidth = slot * 0.6;
    final paint = Paint()..color = barColor;
    for (var i = 0; i < values.length; i++) {
      final h = values[i] / maxValue * size.height;
      final left = slot * i + (slot - barWidth) / 2;
      canvas.drawRRect(
        RRect.fromRectAndRadius(Rect.fromLTWH(left, size.height - h, barWidth, h), const Radius.circular(4)),
        paint,
      );
    }
  }

  @override
  bool shouldRepaint(BarChartPainter old) => !listEquals(old.values, values) || old.barColor != barColor;
}
Stand-in: the same bar chart on a canvas

Common mistakes

  • Zero size: CustomPaint without size or a child paints nothing. Give it a size or wrap it in SizedBox/Expanded.
  • Allocating in paint: creating many Paint, Path or TextPainter objects per frame can cause jank; reuse them when the data has not changed.
  • Wrong shouldRepaint: forgetting a field leaves the picture stale.
  • Forgetting restore() after save(), so transforms and clips leak into later drawing.
  • Doing hit testing by guess: override hitTest in the painter (or use Path.contains) for tappable shapes.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where is the origin (0, 0) of a Flutter canvas?

    As on most screens, x grows right and y grows down from the top-left corner.
  2. 2. What does shouldRepaint(oldDelegate) decide?

    Compare the fields paint() uses. If nothing changed, return false and Flutter skips the work.
  3. 3. Why use canvas.save() and canvas.restore() around a rotation?

    save pushes the current transform and clip; restore pops them.
  4. 4. How do you fill a shape with a gradient?

    A gradient creates a shader for a given rect; the Paint uses it instead of a flat color.

Summary

  • CustomPaint holds a CustomPainter; paint(canvas, size) draws with Paint and canvas calls.
  • The origin is top-left; paths, arcs, gradients (shaders), save/restore, transforms and clips cover most needs.
  • shouldRepaint must compare exactly what you draw from; use repaint: listenables and RepaintBoundary for animation.
  • A chart is arithmetic: scale values to pixels, remembering that y grows downward.

Next: Charts in Flutter