Sub topic 1
How CustomPaint and CustomPainter fit together
Prerequisites
This chapter assumes you already know the following:
- Dart basics: classes, inheritance, and named parameters.
- How to build a Flutter widget tree with
StatelessWidgetandStatefulWidget. - That Flutter layout passes constraints down and sizes up, and what a
Sizeis.
You do not need to know anything about Canvas or Paint yet. The next chapters cover them in detail. This chapter explains how the pieces connect.
What problem CustomPaint solves
Most Flutter UIs are built by combining ready-made widgets such as Container, Row, and Text. Sometimes you need a shape or chart that no widget provides, for example a progress ring, a gauge, or a hand-drawn graph. For these cases Flutter lets you draw pixels yourself.
Two classes do this work together:
CustomPaintis a widget. It takes part in layout and sits in the widget tree like any other widget.CustomPainteris an abstract class that you extend. It holds your drawing code.
The widget decides where and how big the drawing area is. The painter decides what appears inside that area.
The roles of each class
| Class | Kind | Responsibility |
|---|---|---|
| `CustomPaint` | Widget | Takes a size, hosts a painter, and optionally hosts a child |
| `CustomPainter` | Delegate class | Draws with `paint()`, decides repainting with `shouldRepaint()` |
| `Canvas` | Object passed to `paint()` | Provides the drawing methods, such as `drawCircle` |
| `Paint` | Object you create | Holds color, style, stroke width, and shader for one drawing call |
| `Size` | Object passed to `paint()` | Gives the width and height of the area you may draw in |
A CustomPainter is not a widget and does not appear in the widget tree. It is a delegate: the render object that CustomPaint creates calls it when it is time to draw.
A minimal example
The following painter fills a circle in the middle of the available area.
import 'package:flutter/material.dart';
class CirclePainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()
..color = Colors.teal
..style = PaintingStyle.fill;
canvas.drawCircle(size.center(Offset.zero), size.shortestSide / 2, paint);
}
@override
bool shouldRepaint(covariant CirclePainter oldDelegate) => false;
}
// Usage:
// CustomPaint(size: const Size(200, 200), painter: CirclePainter())Here is what each part does:
paint(Canvas canvas, Size size)is the one required drawing method. Flutter calls it whenever the area needs to be drawn.sizeis the area given to the painter. The code uses it instead of hard-coded numbers, so the circle adapts to the available space.size.center(Offset.zero)returns the middle point of the area.size.shortestSide / 2gives the largest radius that still fits.shouldRepaintreturnsfalsebecause this painter has no data that can change.
To show it on screen, wrap it in CustomPaint:
import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp(
home: Scaffold(
body: Center(
child: CustomPaint(
size: const Size(200, 200),
painter: CirclePainter(),
),
),
),
),
);
}
class CirclePainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()
..color = Colors.teal
..style = PaintingStyle.fill;
canvas.drawCircle(size.center(Offset.zero), size.shortestSide / 2, paint);
}
@override
bool shouldRepaint(covariant CirclePainter oldDelegate) => false;
}How the pieces connect at runtime
When you write CustomPaint(painter: ...), the widget creates a render object (RenderCustomPaint). During the paint phase of a frame, that render object gets a Canvas and calls painter.paint(canvas, size).
Two points follow from this:
- You never create a
Canvasyourself. Flutter passes it in, and it is valid only during thepaint()call. Do not store it in a field. paint()records drawing commands. It does not push pixels directly. Flutter later turns the recorded commands into a frame.
The two painters: painter and foregroundPainter
CustomPaint accepts two painters, and the order matters.
painterdraws first, behind the child.foregroundPainterdraws last, in front of the child.
import 'package:flutter/material.dart';
class BackgroundPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
canvas.drawRect(Offset.zero & size, Paint()..color = Colors.grey.shade200);
}
@override
bool shouldRepaint(covariant BackgroundPainter oldDelegate) => false;
}
class BadgePainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
canvas.drawCircle(
Offset(size.width - 8, 8),
8,
Paint()..color = Colors.red,
);
}
@override
bool shouldRepaint(covariant BadgePainter oldDelegate) => false;
}
class LayeredExample extends StatelessWidget {
const LayeredExample({super.key});
@override
Widget build(BuildContext context) {
return CustomPaint(
painter: BackgroundPainter(),
foregroundPainter: BadgePainter(),
child: const Padding(
padding: EdgeInsets.all(24),
child: Text('Inbox'),
),
);
}
}The grey background is drawn first, then the Text child, then the red badge on top. This pattern is useful for decorations that should overlap the child.
How the size is chosen
CustomPaint follows simple sizing rules. The details come in the next chapter, but you need the basics now to avoid the most common error.
- If
childis set,CustomPainttakes the size of the child. Thesizeargument is ignored. - If there is no child, it uses the
sizeargument, limited by the incoming constraints. - The default
sizeisSize.zero. With no child and no size, the painter gets a zero-sized area, so nothing is visible.
import 'package:flutter/material.dart';
class CirclePainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
canvas.drawCircle(
size.center(Offset.zero),
size.shortestSide / 2,
Paint()..color = Colors.teal,
);
}
@override
bool shouldRepaint(covariant CirclePainter oldDelegate) => false;
}
class SizingExamples extends StatelessWidget {
const SizingExamples({super.key});
@override
Widget build(BuildContext context) {
return Column(
children: [
// Draws nothing visible: size defaults to Size.zero.
CustomPaint(painter: CirclePainter()),
// Draws in a 120 x 120 area.
CustomPaint(size: const Size(120, 120), painter: CirclePainter()),
// Fills the space the parent gives it.
SizedBox(
width: 80,
height: 80,
child: CustomPaint(painter: CirclePainter()),
),
],
);
}
}In the third case, SizedBox forces tight constraints of 80 by 80. A CustomPaint without a child must fit within those constraints, so it becomes 80 by 80 even though its own size is zero.
What shouldRepaint and the delegate model mean
The painter is a delegate, so Flutter keeps the old one around when the widget rebuilds. When a parent rebuilds and passes a new painter instance, Flutter calls shouldRepaint(oldDelegate) on the new painter. The result decides whether the area is drawn again.
- Return
falsewhen nothing that affects the drawing has changed. - Return
truewhen any input has changed.
Because a rebuild creates a new painter object, you cannot compare painters by identity. Compare the fields that affect drawing. A later chapter covers this in depth. For now, the rule is that a painter with no inputs can return false, and a painter with inputs should compare them.
Common errors
- Nothing appears. The most frequent cause is a zero size. Set
size, giveCustomPainta child, or place it inside a widget that provides constraints. - Drawing outside the area. By default,
CustomPaintdoes not clip. Anything you draw beyondsizecan show up outside the area. A later chapter covers clipping. - Storing the canvas. The canvas is valid only during
paint(). Keep drawing inside that method. - Allocating heavily in paint().
paint()can run every frame. Avoid slow work there, such as parsing data or building large objects that never change. - Forgetting
covariant. TheshouldRepaintsignature usescovariantso you can write the parameter as your own painter type. Without it, you must castoldDelegateyourself.
Putting it together
The flow for any custom drawing is the same:
- Write a class that extends
CustomPainter. - Implement
paint(Canvas canvas, Size size)and draw withPaintobjects. - Implement
shouldRepaintso Flutter knows when to redraw. - Place a
CustomPaintwidget in the tree, pass your painter, and make sure it has a size.
Exercise
You write CustomPaint(painter: MyPainter()) with no child and no size, and place it directly inside a Column. Nothing appears on screen, and paint() runs without errors. Why, and what are two ways to fix it?
Show answer
With no child and no size, CustomPaint uses the default Size.zero, so the painter receives an area of zero width and height and anything it draws is not visible. Fix it by passing a size, for example size: const Size(200, 200), or by wrapping the CustomPaint in a widget that gives it constraints, such as SizedBox(width: 200, height: 200, child: ...). Giving it a child also works, because the widget then takes the child's size.
Exercise
A painter draws a background rectangle, and you want a red dot to appear on top of a Text child. Which CustomPaint parameter should draw the dot, and why?
Show answer
Use foregroundPainter. The painter parameter draws before the child, so the dot would be hidden behind the text. The foregroundPainter draws after the child, so the dot appears in front.