Sub topic 3
Canvas and Paint: the two core objects
This chapter assumes you can write a basic CustomPainter subclass and place it in a CustomPaint widget. It also assumes you know how Size and Offset work. Here you learn what Canvas and Paint each are, how they split the work of drawing, and which mistakes cause most painter bugs.
The division of labor
Every drawing call in Flutter combines two objects:
Canvassays what to draw and where. It exposes methods such asdrawCircle,drawLine,drawPath, anddrawParagraph. It also holds the current transform and clip.Paintsays how to draw. It holds the color, fill or stroke style, stroke width, shader, blend mode, and anti-aliasing flag.
Almost every draw* method takes the geometry plus a Paint. If you can't tell which object a setting belongs to, ask whether it describes a shape (Canvas) or its appearance (Paint). Position, rotation, and clipping belong to the canvas. Color, thickness, and gradients belong to the paint.
| Question | Object | Example |
|---|---|---|
| Where is the shape? | `Canvas` | `drawCircle(center, radius, paint)` |
| Is the whole drawing rotated? | `Canvas` | `canvas.rotate(0.5)` |
| Is the drawing cut off? | `Canvas` | `canvas.clipRect(rect)` |
| What color is it? | `Paint` | `paint.color = Colors.red` |
| Is it filled or outlined? | `Paint` | `paint.style = PaintingStyle.stroke` |
| How thick is the outline? | `Paint` | `paint.strokeWidth = 4` |
What the Canvas really is
You do not draw pixels when you call canvas.drawCircle. The Canvas passed to paint() is a recorder. Each call appends a command to a display list. When paint() returns, the recorded commands become a picture. Flutter attaches that picture to a layer, and the engine rasterizes it later, usually on a separate raster thread.
This model has four consequences:
- You cannot read pixels back. There is no "what color is at (10, 10)?" call. If you need that information, keep the data model yourself.
- Do not keep the canvas. The canvas is valid only during
paint(). Storing it in a field and drawing later fails or draws nothing. - Calls are cheap, rasterization is not. Recording a thousand
drawCirclecalls is fast in Dart. The cost shows up when the engine fills the pixels, so a few large blurred or layered operations can cost more than many small ones. - Order is the only depth. There is no z-index. Later calls paint over earlier ones.
A first complete example
This program draws a filled circle, outlines it with the same Paint, and adds a white bar. It runs as shown.
import 'package:flutter/material.dart';
void main() => runApp(
const MaterialApp(
home: Scaffold(body: Center(child: BadgeDemo())),
),
);
class BadgeDemo extends StatelessWidget {
const BadgeDemo({super.key});
@override
Widget build(BuildContext context) {
return CustomPaint(
size: const Size(200, 200),
painter: BadgePainter(color: Colors.teal),
);
}
}
class BadgePainter extends CustomPainter {
BadgePainter({required this.color});
final Color color;
@override
void paint(Canvas canvas, Size size) {
final center = size.center(Offset.zero);
final radius = size.shortestSide / 2 - 4;
// 1. Fill. A new Paint is opaque black and set to fill by default.
final paint = Paint()..color = color;
canvas.drawCircle(center, radius, paint);
// 2. Outline. Mutate the same Paint and draw again.
paint
..color = Colors.black
..style = PaintingStyle.stroke
..strokeWidth = 4;
canvas.drawCircle(center, radius, paint);
// 3. A white bar drawn on top of both circles.
paint.color = Colors.white;
canvas.drawLine(
Offset(center.dx - radius / 2, center.dy),
Offset(center.dx + radius / 2, center.dy),
paint,
);
}
@override
bool shouldRepaint(covariant BadgePainter oldDelegate) =>
oldDelegate.color != color;
}Step 2 changes the Paint after the first circle has been drawn. The first circle keeps its teal fill. The canvas copies the paint's settings when you make each call, so later mutations never change commands already recorded. This is why reusing one Paint object across several calls is safe.
Paint defaults and the properties you will use first
A new Paint() has these defaults:
coloris0xFF000000, which is opaque black.styleisPaintingStyle.fill.strokeWidthis0.0. In stroke style, a width of zero draws a hairline that is one device pixel wide, not invisible.isAntiAliasistrue, so edges are smoothed.
Setting style to stroke and forgetting strokeWidth produces a very thin line. That is a hairline, not a missing shape.
Other properties come up in later chapters. shader is used for gradients, blendMode for compositing, maskFilter for blur, and strokeCap and strokeJoin for line ends. At this stage, remember that all of them live on Paint, and none of them live on the shape.
Color needs one note. The Color class stores alpha in the top byte. const Color(0x990000FF) is a translucent blue. Use alpha-aware constructors when you want transparency, and do not assume that Paint.color multiplies with other opacity settings. It does not. Whatever alpha the color carries is the alpha that is drawn.
Draw order and overlap
Because there is no z-index, you control stacking by ordering your calls. The next painter draws a red square and then a translucent blue square over it.
import 'package:flutter/material.dart';
void main() => runApp(
MaterialApp(
home: Scaffold(
body: Center(
child: CustomPaint(
size: const Size(200, 200),
painter: OverlapPainter(),
),
),
),
),
);
class OverlapPainter extends CustomPainter {
// One Paint, created once per painter instance, reused in every paint().
final Paint _paint = Paint();
@override
void paint(Canvas canvas, Size size) {
final back = Rect.fromLTWH(0, 0, size.width * 0.6, size.height * 0.6);
final front = back.shift(Offset(size.width * 0.3, size.height * 0.3));
canvas.drawRect(back, _paint..color = const Color(0xFFE53935));
canvas.drawRect(front, _paint..color = const Color(0x990000FF));
}
@override
bool shouldRepaint(covariant OverlapPainter oldDelegate) => false;
}The red square shows through the blue one in the overlap region, because the blue color has alpha 0x99. If you swap the two drawRect calls, the red square moves to the front and covers the blue one.
If you need something behind or in front of a child widget, CustomPaint has two slots. painter draws before the child, and foregroundPainter draws after it. Within one painter, ordering is still the order of your calls.
Where to create Paint objects
paint() can run many times per second during an animation. Creating a Paint inside it allocates on every frame. For one or two objects this is harmless. Flutter's garbage collector handles short-lived objects well. It matters when you create hundreds per frame, for example inside a loop over data points.
Choose by what the paint depends on:
- If the paint's settings are fixed, store it in a
finalfield on the painter, asOverlapPainterdoes above. - If the paint depends on the painter's inputs, build it in
paint(), or in the constructor if you only need it once. - If many calls share most settings, create one
Paintand mutate only the properties that change, as inBadgePainter.
A caution applies to the field approach. A painter instance may be replaced when the widget rebuilds, so a field paint lives only as long as that instance. Do not store state you need to survive a rebuild on a painter. Keep that state in the widget or its State.
Edge cases and common errors
- Drawing outside the bounds.
CustomPaintdoes not clip its painter by default. A shape drawn at negative coordinates, or beyondsize, can appear over neighboring widgets. Callcanvas.clipRect(Offset.zero & size)at the start ofpaint()if you need a hard boundary. Clipping is covered in a later chapter. - Unbounded size. If
CustomPainthas no child and nosize, it takes size zero, and nothing visible is drawn. Give it asize, a child, or a parent with tight constraints. - Everything is black. You forgot to set
color. The default is opaque black, not "inherit from theme." - Invisible stroke or fill. Check
style. APaintin fill style ignoresstrokeWidth, and a stroke-style paint draws only the outline. - A stale picture. If the painter's inputs change but
shouldRepaintreturnsfalse, the old picture stays on screen. The next chapters cover how to avoid this.
Exercise
In the BadgePainter example, the Paint is changed from teal fill to black stroke after the first drawCircle call. Why does the first circle stay teal, and what would you change to draw the second circle with a 4-pixel black outline but a different cap style?
Show answer
The canvas records the paint's settings when each draw call is made, so mutating the Paint afterward does not affect commands already recorded. To change the cap style, set paint.strokeCap = StrokeCap.round (or another StrokeCap) in the same cascade as style and strokeWidth before the second call. Note that caps only affect the ends of open lines and paths, so a closed circle would look the same.
Exercise
A painter draws a stroked rectangle but only a faint thin line appears. The code sets style = PaintingStyle.stroke and never sets strokeWidth. Why is the line thin, and how do you fix it?
Show answer
The default strokeWidth is 0.0, which draws a hairline one device pixel wide. Set strokeWidth to the thickness you want in logical pixels, for example paint.strokeWidth = 3.