Sub topic 13
Keeping painters fast with RepaintBoundary
This chapter assumes you can write a CustomPainter with paint and shouldRepaint, and that you have driven a painter from an AnimationController through the repaint parameter. You don't need to know Flutter's rendering internals. The chapter explains the parts that matter for painting.
How repaints spread
Flutter draws each frame in phases: build, layout, paint, then compositing. Painting walks the render tree and records drawing commands into layers. A render object that needs to redraw calls markNeedsPaint. That call does not repaint only that object. It walks up the tree until it reaches the nearest ancestor that is a repaint boundary. Then it marks that boundary dirty.
When the boundary repaints, everything in its subtree repaints too, including siblings that did nothing. A child that is its own repaint boundary and is not dirty keeps its recorded layer and is skipped.
By default, RenderCustomPaint is not a repaint boundary. An animated painter inside a large page therefore dirties the whole region up to the nearest boundary, such as the one the page route provides. Every static sibling in that region runs its paint again on every frame.
What RepaintBoundary does
RepaintBoundary is a widget whose render object has isRepaintBoundary set to true. It paints its child into a separate layer. Two things follow from that:
- A repaint request inside the boundary stops there. Ancestors and siblings are not marked dirty.
- If something outside changes, the boundary's layer is reused and its child's
paintis not called.
The most common placement is around the animated part. One boundary around a spinner protects every static widget next to it.
Measuring the problem first
Don't add boundaries by guesswork. Check whether the static content is actually being repainted. This example has a static grid and a spinning square. The grid counts its paint calls so you can see the difference in the console.
import 'dart:math' as math;
import 'package:flutter/material.dart';
void main() {
// Set useBoundary to false and compare the console output.
runApp(const MaterialApp(
home: Scaffold(body: Center(child: BoundaryDemo(useBoundary: true))),
));
}
class GridPainter extends CustomPainter {
int paintCount = 0;
final Paint _line = Paint()
..color = Colors.black26
..strokeWidth = 1;
@override
void paint(Canvas canvas, Size size) {
paintCount++;
debugPrint('GridPainter.paint #$paintCount');
for (double x = 0; x <= size.width; x += 10) {
canvas.drawLine(Offset(x, 0), Offset(x, size.height), _line);
}
for (double y = 0; y <= size.height; y += 10) {
canvas.drawLine(Offset(0, y), Offset(size.width, y), _line);
}
}
@override
bool shouldRepaint(covariant GridPainter oldDelegate) => false;
}
class SquarePainter extends CustomPainter {
SquarePainter(this.animation) : super(repaint: animation);
final Animation<double> animation;
@override
void paint(Canvas canvas, Size size) {
canvas.save();
canvas.translate(size.width / 2, size.height / 2);
canvas.rotate(animation.value * 2 * math.pi);
canvas.drawRect(
Rect.fromCenter(center: Offset.zero, width: 80, height: 80),
Paint()..color = Colors.orange,
);
canvas.restore();
}
@override
bool shouldRepaint(covariant SquarePainter oldDelegate) =>
oldDelegate.animation != animation;
}
class BoundaryDemo extends StatefulWidget {
const BoundaryDemo({super.key, required this.useBoundary});
final bool useBoundary;
@override
State<BoundaryDemo> createState() => _BoundaryDemoState();
}
class _BoundaryDemoState extends State<BoundaryDemo>
with SingleTickerProviderStateMixin {
late final AnimationController _controller = AnimationController(
vsync: this,
duration: const Duration(seconds: 2),
)..repeat();
final GridPainter _grid = GridPainter();
late final SquarePainter _square = SquarePainter(_controller);
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final square = CustomPaint(size: const Size(200, 200), painter: _square);
return Stack(
children: [
CustomPaint(size: const Size(200, 200), painter: _grid),
widget.useBoundary ? RepaintBoundary(child: square) : square,
],
);
}
}With useBoundary: false, the console prints a new GridPainter.paint line roughly 60 times per second, even though shouldRepaint returns false. That is expected. shouldRepaint is consulted only when a widget rebuild supplies a new painter. The repaint listenable calls markNeedsPaint directly and skips that check. With useBoundary: true, the grid prints once.
Seeing boundaries on screen
Two debugging switches help when you can't add print statements:
debugRepaintRainbowEnabled = true(frompackage:flutter/rendering.dart) draws a changing colored border over every boundary layer each time it repaints. A boundary that flickers every frame is repainting every frame.- The DevTools performance overlay shows the raster and UI thread times per frame.
Where to put boundaries
| Situation | Placement | Reason |
|---|---|---|
| One animated painter next to static content | Around the animated painter | Its repaints stop at its own layer |
| Expensive static painter (chart, map) beside changing UI | Around the static painter | Its layer is reused instead of redrawn |
| Many identical items in a scrolling list | Usually nothing to add | `ListView` and `GridView` wrap children in boundaries by default |
| A painter that changes every frame and is the only thing on screen | None | Nothing is shared with it, so there is nothing to protect |
Costs of boundaries
A boundary is not free. Each one is a separate layer that Flutter has to manage. A layer that is cached uses memory, and a screen full of tiny boundaries adds compositing work that can exceed the painting it saves. Use boundaries to separate content that changes at different rates, and don't use them as decoration.
A boundary also does not make a painter cheaper. It only stops unrelated repaints from reaching it. If the painter itself changes every frame, its paint still runs every frame, so it must be cheap on its own.
Raster cache hints
CustomPaint has two flags that tell the engine how to treat its picture:
isComplex: truesays the painting is expensive, so the engine should prefer to cache the rasterized result.willChange: truesays the painting is about to change, so the engine should not bother caching it.
These are hints. Use them sparingly and verify the effect in the performance overlay. The usual case is isComplex: true on a heavy, rarely changing painter that sits inside a boundary.
Keeping paint() cheap
The paint method runs on the UI thread and has about 16 ms per frame at 60 Hz, less on high-refresh displays. The rules below apply no matter how many boundaries you have.
- Create
Paintobjects once, as fields, when their settings don't change. Update only the properties that do change. - Cache
Pathobjects and shaders that depend only on size, and rebuild them when the size changes. - Call
TextPainter.layoutonly when the text or the width changes, not on every frame. - Avoid
saveLayerand blend modes that force offscreen buffers unless the effect needs them. They allocate a temporary surface on each call. - Draw only what is visible. When a painter covers a large scrolling area, skip items outside the clip bounds.
This painter caches its star outline for the current size and rebuilds it only when the size changes.
import 'dart:math' as math;
import 'package:flutter/material.dart';
class StarPainter extends CustomPainter {
StarPainter({required this.color});
final Color color;
late final Paint _paint = Paint()..color = color;
Path? _path;
Size? _pathSize;
Path _starFor(Size size) {
final cached = _path;
if (cached != null && _pathSize == size) {
return cached;
}
final center = size.center(Offset.zero);
final outer = size.shortestSide / 2;
final path = Path();
for (var i = 0; i < 10; i++) {
final radius = i.isEven ? outer : outer * 0.4;
final angle = -math.pi / 2 + i * math.pi / 5;
final point =
center + Offset(math.cos(angle), math.sin(angle)) * radius;
if (i == 0) {
path.moveTo(point.dx, point.dy);
} else {
path.lineTo(point.dx, point.dy);
}
}
path.close();
_path = path;
_pathSize = size;
return path;
}
@override
void paint(Canvas canvas, Size size) {
canvas.drawPath(_starFor(size), _paint);
}
@override
bool shouldRepaint(covariant StarPainter oldDelegate) =>
oldDelegate.color != color;
}The caches live on the painter instance. When a parent rebuild creates a new StarPainter, the new instance starts with empty caches. That costs one path build, which is fine. It would become a cost if the parent rebuilt on every frame, so keep painters in State fields when the parent rebuilds often.
Common mistakes
- Trusting
shouldRepaintto protect against animation repaints. It is not called when therepaintlistenable fires. Use a boundary for that. - Wrapping everything in
RepaintBoundary. This creates many layers and can slow compositing. Add a boundary only where profiling shows repaints crossing between areas. - Allocating inside
paint. Creating newPaint,Path,Shader, orTextPainterobjects every frame produces garbage and frame-time spikes. - Rebuilding the painter in
buildfor no reason. Each new instance loses its caches and forces ashouldRepaintcomparison. - Measuring in debug mode. Debug timings are not representative of release performance.
Exercise
A screen shows a complex static chart in one CustomPaint and a small animated pulse indicator in another, both inside the same Column. The chart's paint method runs on every animation frame even though its shouldRepaint returns false. What is the smallest change that stops this, and how do you confirm it worked?
Show answer
Wrap the animated pulse CustomPaint in a RepaintBoundary. The pulse's markNeedsPaint calls then stop at its own layer and no longer dirty the region that contains the chart. To confirm, count paint calls in the chart painter with a debugPrint (it should print once instead of every frame), or set debugRepaintRainbowEnabled to true and check that only the pulse's border changes color.
Exercise
Why does a painter whose shouldRepaint returns false still repaint every frame when it is driven through super(repaint: animation)?
Show answer
shouldRepaint is only called when a rebuild gives the CustomPaint widget a new painter instance. The repaint listenable calls markNeedsPaint on the render object directly, so the comparison never happens and the painter's paint method runs on each tick. Limiting the effect to the animated painter requires a RepaintBoundary.