Flutter widgets cover most interfaces, but some visuals have no widget: a gauge needle, a waveform, a custom chart, a game board, or a progress ring with a gradient. Stacking containers to fake those shapes produces fragile layouts. CustomPainter solves the problem directly by giving a widget a canvas to draw on, so one paint pass renders lines, arcs, paths, and text at exact coordinates.
This guide covers the paint and shouldRepaint contract, paths and curves, drawing text, hit testing, animation with a listenable, and the performance rules that keep custom drawing at 60 frames per second. The official custom painting documentation is the reference for the canvas API used throughout.
What is CustomPainter in Flutter?
CustomPainter is a Flutter class that draws custom two-dimensional graphics onto a Canvas inside a CustomPaint widget. A developer extends CustomPainter, overrides the paint method to issue drawing commands, and overrides shouldRepaint to declare whether new painter data requires a redraw. CustomPaint then sizes the canvas through its size or child, and the painter renders shapes that no standard widget provides, such as arcs, bezier curves, polygons, and freehand strokes.
Use CustomPainter when a visual is fundamentally drawn rather than laid out. A progress ring, a sparkline, a dial, or a board with hundreds of cells belongs on a canvas, because one painter replaces dozens of widgets and paints in a single pass. Use normal widgets when the interface needs text input, scrolling, or accessibility semantics. Many screens combine both: widgets own layout and interaction, while a painter draws the one custom visual inside a fixed-size box.
How do you create a first CustomPainter?
Create a first CustomPainter by extending CustomPainter, drawing in paint with a Paint object, and placing the painter inside a CustomPaint widget with an explicit size. The paint method receives a Canvas and the Size of the drawing area; coordinates use logical pixels with the origin at the top-left, x to the right and y downward. A Paint carries color, stroke width, and style, and canvas methods such as drawCircle and drawLine consume it.
import 'package:flutter/material.dart';
class RingPainter extends CustomPainter {
const RingPainter({required this.progress, required this.color});
final double progress;
final Color color;
@override
void paint(Canvas canvas, Size size) {
final center = Offset(size.width / 2, size.height / 2);
final radius = size.shortestSide / 2 - 8;
final track = Paint()
..color = color.withValues(alpha: 0.15)
..style = PaintingStyle.stroke
..strokeWidth = 12
..strokeCap = StrokeCap.round;
final arc = Paint()
..color = color
..style = PaintingStyle.stroke
..strokeWidth = 12
..strokeCap = StrokeCap.round;
canvas.drawCircle(center, radius, track);
canvas.drawArc(
Rect.fromCircle(center: center, radius: radius),
-1.5708, // start at the top, in radians
6.2832 * progress.clamp(0.0, 1.0),
false,
arc,
);
}
@override
bool shouldRepaint(RingPainter oldDelegate) =>
oldDelegate.progress != progress || oldDelegate.color != color;
}
Use the painter with a fixed size:
const SizedBox(
width: 180,
height: 180,
child: CustomPaint(
painter: RingPainter(progress: 0.72, color: Colors.teal),
),
)
Two details matter in every painter. The radius derives from size.shortestSide, so the ring stays circular inside a rectangular box. And drawArc measures angles in radians from the three o clock position, sweeping clockwise, so the start angle is negative pi over two to begin at the top.
What does shouldRepaint actually control?
shouldRepaint controls whether Flutter repaints a CustomPaint when its painter instance changes during a rebuild. Flutter compares the new painter with the previous painter by calling shouldRepaint on the new instance, passing the old painter as the argument. Returning true schedules a repaint; returning false reuses the existing picture and skips the paint method entirely. A correct shouldRepaint compares every field the paint method reads, because a missing comparison produces stale drawings that never update.
Write shouldRepaint as an explicit field-by-field comparison, never as an unconditional true. An unconditional true repaints on every rebuild and wastes raster time; an unconditional false freezes the drawing, the classic reason a custom chart ignores new data. For list fields, use a deep equality check or a version number, because two lists with equal contents still compare as different objects in Dart. When the painter holds an Animation, pass it to the super constructor instead, and Flutter repaints whenever it notifies.
How do paths, curves, and gradients work?
A Path in Flutter is a sequence of connected line and curve segments that a canvas can stroke, fill, or clip against. Build a path with moveTo to lift the pen, lineTo for straight segments, quadraticBezierTo and cubicTo for curves, and close to join the end back to the start. Fill a path with PaintingStyle.fill for solid shapes, or stroke the same path with PaintingStyle.stroke and a stroke width for outlines. Gradients attach through Paint.shader, using LinearGradient or RadialGradient created against the current size.
class WavePainter extends CustomPainter {
const WavePainter({required this.values, required this.color});
final List<double> values;
final Color color;
@override
void paint(Canvas canvas, Size size) {
if (values.length < 2) return;
final stepX = size.width / (values.length - 1);
Offset pointAt(int i) =>
Offset(stepX * i, size.height - values[i] * size.height);
final line = Path()..moveTo(pointAt(0).dx, pointAt(0).dy);
for (var i = 1; i < values.length - 1; i++) {
final mid = Offset(
(pointAt(i).dx + pointAt(i + 1).dx) / 2,
(pointAt(i).dy + pointAt(i + 1).dy) / 2,
);
line.quadraticBezierTo(pointAt(i).dx, pointAt(i).dy, mid.dx, mid.dy);
}
line.lineTo(pointAt(values.length - 1).dx, pointAt(values.length - 1).dy);
final fill = Path.from(line)
..lineTo(size.width, size.height)
..lineTo(0, size.height)
..close();
final rect = Offset.zero & size;
final fillPaint = Paint()
..shader = LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [color.withValues(alpha: 0.35), color.withValues(alpha: 0.02)],
).createShader(rect);
canvas.drawPath(fill, fillPaint);
canvas.drawPath(
line,
Paint()
..color = color
..style = PaintingStyle.stroke
..strokeWidth = 2.5
..strokeCap = StrokeCap.round,
);
}
@override
bool shouldRepaint(WavePainter oldDelegate) =>
oldDelegate.values != values || oldDelegate.color != color;
}
The midpoint technique produces a smooth curve through every data point without overshoot, which suits sparklines and health charts. The fill path copies the line path and extends it to the bottom corners, so the gradient area always matches the line. Create shaders inside paint from the current size, because a shader built for one size stretches incorrectly after a resize.
How do you draw text on a canvas?
Draw text on a canvas with a TextPainter, because Canvas has no direct text method handling fonts, wrapping, and direction. Create a TextPainter with a TextSpan and a text direction, call layout with a maximum width, then paint it at an offset. Measure the laid-out size first to center the text against a shape, and dispose the TextPainter after use.
void drawCenteredLabel(Canvas canvas, Size size, String label) {
final textPainter = TextPainter(
text: TextSpan(
text: label,
style: const TextStyle(
color: Colors.black87,
fontSize: 28,
fontWeight: FontWeight.w700,
),
),
textDirection: TextDirection.ltr,
)..layout(maxWidth: size.width);
final offset = Offset(
(size.width - textPainter.width) / 2,
(size.height - textPainter.height) / 2,
);
textPainter.paint(canvas, offset);
textPainter.dispose();
}
Text inside a painter does not participate in accessibility or text scaling automatically. Pass a scaled font size from MediaQuery.textScaler into the painter, and wrap the CustomPaint in Semantics so screen readers announce the value the drawing shows. For axis labels, a widget overlay over the canvas is often simpler; the responsive design guide covers that overlay approach.
How do you animate a CustomPainter?
Animate a CustomPainter by passing an Animation as the repaint listenable to the CustomPainter super constructor, so Flutter repaints on every animation tick without rebuilding the widget tree. The painter reads the animation value inside paint, and shouldRepaint can return false because the listenable drives repaints directly. This pattern keeps animation cost inside the paint phase, which is exactly where frame-driven drawing belongs.
class PulsePainter extends CustomPainter {
PulsePainter({required this.animation, required this.color})
: super(repaint: animation);
final Animation<double> animation;
final Color color;
@override
void paint(Canvas canvas, Size size) {
final center = Offset(size.width / 2, size.height / 2);
final base = size.shortestSide / 2;
final radius = base * (0.55 + 0.35 * animation.value);
canvas.drawCircle(
center,
radius,
Paint()..color = color.withValues(alpha: 0.25),
);
canvas.drawCircle(center, base * 0.3, Paint()..color = color);
}
@override
bool shouldRepaint(PulsePainter oldDelegate) =>
oldDelegate.color != color;
}
Drive the animation from a controller in the widget state, dispose it with the state, and pass the same animation instance across rebuilds. The breathing pacer guide applies the same listenable pattern to a meditation circle, and the animations for beginners guide covers controllers, curves, and tweens.
How do you handle taps on painted shapes?
Handle taps on painted shapes with a GestureDetector around the CustomPaint, then convert the tap offset into the painter coordinate space and test it against the same geometry the painter draws. A canvas has no built-in hit testing per shape, so the painter geometry and the hit-test geometry must come from one shared model. Store the shape data in a plain Dart class, let the painter render from that model, and let the tap handler query the model with methods such as Rect.contains or a distance check.
class BoardModel {
BoardModel(this.cellSize);
final double cellSize;
final Set<(int, int)> filled = {};
(int, int)? cellAt(Offset offset, Size size) {
if (offset.dx < 0 || offset.dy < 0) return null;
if (offset.dx >= size.width || offset.dy >= size.height) return null;
return (offset.dy ~/ cellSize, offset.dx ~/ cellSize);
}
void toggle(Offset offset, Size size) {
final cell = cellAt(offset, size);
if (cell == null) return;
if (!filled.remove(cell)) filled.add(cell);
}
}
Keep one source of truth for geometry. When the painter and the tap handler compute cell rectangles differently, taps land one cell away from the visual target after any size change. A shared model also makes drawing logic unit-testable without a canvas. The bubble shooter guide uses the same separation, rendering a hex board with one painter while a grid model owns the rules.
What are the performance rules for CustomPainter?
The performance rules for CustomPainter are simple: paint only when data changes, precompute expensive objects outside paint, wrap the CustomPaint in a RepaintBoundary, and keep per-frame work proportional to what is visible. Allocating gradients, paths, and text painters every frame creates garbage-collector pressure on the raster thread. Redrawing a whole board for one changed cell wastes the frame budget that 60 frames per second allows, roughly 16 milliseconds per frame.
| Technique | Effect | When to use it |
|---|---|---|
| Field-by-field shouldRepaint | Skips paint when data is unchanged | Every painter |
| RepaintBoundary around CustomPaint | Isolates repaint from parent repaints | Animated or frequently updated painters |
| Precomputed Paint and Path objects | Removes per-frame allocation | Static shapes and repeated frames |
| Animation as repaint listenable | Repaints without widget rebuilds | Any animated painter |
| Single painter for many shapes | One paint pass instead of many widgets | Boards, charts, waveforms |
Measure before optimizing. DevTools shows raster time per frame, and a painter under a few milliseconds needs no further work. When raster time grows, check shadow and blur first, because MaskFilter blur and large shadows are the most expensive canvas operations on low-end Android devices. Prefer solid fills and simple gradients, cache a static background when it never changes, and move heavy geometry computation into the model, where it runs once per data change instead of once per frame.
When should you avoid CustomPainter?
Avoid CustomPainter when a standard widget already renders the visual, when content needs text input or selection, or when accessibility semantics carry the meaning. A rounded rectangle with a border is a Container with BoxDecoration, not a painter. A paragraph is a Text widget. A list of tappable rows is a ListView, not a canvas with manual hit testing.
Choose CustomPainter when the visual is a drawing: charts, gauges, rings, waveforms, boards, signatures, and animated shapes widgets cannot express. That boundary keeps painters small and fast, and keeps the rest of the interface in widgets where Flutter handles layout, semantics, and input. If your project needs a custom chart, gauge, or game board in Flutter, Get in touch and let's talk about your project.
Originally published at uzairxdev.online
Top comments (0)