Sub topic 12
Rebuilds are not repaints: when RepaintBoundary helps
This chapter assumes you have read the earlier chapters on how setState marks elements dirty, how to measure rebuilds, and how to narrow rebuild scope. It also assumes you can run an app in profile mode. The previous chapters cut the cost of the build phase. This chapter covers the next phase, painting, which can still be expensive when rebuilds are already minimal.
Rebuild, relayout and repaint are different work
Each frame can run several phases, and each phase marks its own objects dirty.
| Phase | What runs | What marks it dirty | What it costs |
|---|---|---|---|
| Build | `build` methods on dirty elements | `setState`, inherited widget changes, listenable notifications | Dart object creation and element diffing |
| Layout | `performLayout` on render objects | A size or constraint change (`markNeedsLayout`) | Measuring and positioning children |
| Paint | `paint` on render objects | A visual change (`markNeedsPaint`) | Recording drawing commands into layers |
| Composite and raster | Layer tree to GPU | New or changed layers | GPU work on the raster thread |
A rebuild does not imply a repaint. When a widget rebuilds, Flutter compares the new widget with the old one. If the widget type and key match, it calls updateRenderObject on the existing render object. Most render objects call markNeedsPaint only when a property really changed. A rebuilt Padding with identical values repaints nothing.
The reverse also holds. A repaint does not need a rebuild. An AnimationController driving a CustomPaint through its repaint listenable, or a scroll offset moving a viewport, repaints without running any build method.
So a screen can show a low rebuild count in your audit and still drop frames, because paint time is spent somewhere the rebuild tools do not look.
How paint dirtiness spreads
When a render object calls markNeedsPaint, Flutter does not repaint only that object. It walks up the render tree until it reaches the nearest ancestor that is a repaint boundary. That ancestor is added to the list of objects to repaint. When it repaints, it calls paint on all of its descendants, including those that did not change.
A repaint boundary is a render object whose isRepaintBoundary is true. It paints into its own layer. Two things follow:
- A change inside the boundary cannot dirty anything outside it. The walk up stops there.
- A boundary that is not dirty keeps its layer from the last frame, and the parent reuses that layer without calling the boundary's
paint.
Flutter already inserts boundaries in several places. The root of the app has one, and each route's content is wrapped in one. ListView and GridView wrap each child in a RepaintBoundary by default through the addRepaintBoundaries: true parameter. Several framework widgets, such as Scrollable, also create their own layers. You add a boundary yourself when your screen has a region that repaints often next to a region that is costly to paint.
Seeing repaints
The rebuild tools from earlier chapters do not show paint activity. Use these instead:
debugRepaintRainbowEnabledfrompackage:flutter/rendering.dartdraws a rotating colored border over each repainted layer. A layer that changes color every frame is repainting every frame.- In DevTools, the Flutter Inspector has a "Highlight repaints" toggle that does the same thing without a code change.
- The Performance view shows UI-thread and raster-thread frame times. Check these in profile mode, never in debug mode.
- A
debugPrintinside aCustomPainter.paintmethod tells you exactly how often that painter runs.
The following app logs each paint of an expensive grid while a progress bar animates beside it. Run it twice, once with useBoundary: false and once with true.
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
void main() {
// Debug builds only: draws a colored border over each repainted layer.
debugRepaintRainbowEnabled = true;
runApp(const MaterialApp(
home: Scaffold(body: Dashboard(useBoundary: true)),
));
}
class Dashboard extends StatelessWidget {
const Dashboard({super.key, required this.useBoundary});
final bool useBoundary;
@override
Widget build(BuildContext context) {
const grid = CustomPaint(
painter: GridPainter(),
size: Size.infinite,
);
return Column(
children: [
// Indeterminate: this bar repaints on every frame.
const LinearProgressIndicator(),
Expanded(
child: useBoundary ? const RepaintBoundary(child: grid) : grid,
),
],
);
}
}
class GridPainter extends CustomPainter {
const GridPainter();
@override
void paint(Canvas canvas, Size size) {
debugPrint('GridPainter.paint ${size.width}x${size.height}');
final line = Paint()..color = Colors.black26;
for (double x = 0; x < size.width; x += 8) {
canvas.drawLine(Offset(x, 0), Offset(x, size.height), line);
}
for (double y = 0; y < size.height; y += 8) {
canvas.drawLine(Offset(0, y), Offset(size.width, y), line);
}
}
@override
bool shouldRepaint(GridPainter oldDelegate) => false;
}Without the boundary, the console prints GridPainter.paint on every animation frame. The progress bar and the grid share the route's layer, so when the bar dirties that layer, the grid is painted again. With the boundary, the grid paints once, and the layer is reused after that.
No widget rebuilds here after the first frame. The progress bar's animation calls markNeedsPaint directly, so a rebuild counter would report nothing while the grid repaints constantly.
Repainting without rebuilding
For animation that only changes pixels, you can skip the build phase entirely. Pass the animation to the painter's repaint parameter. The render object then calls markNeedsPaint on each tick, and no widget rebuilds.
import 'package:flutter/material.dart';
class SweepPainter extends CustomPainter {
SweepPainter(this.animation) : super(repaint: animation);
final Animation<double> animation;
@override
void paint(Canvas canvas, Size size) {
final x = size.width * animation.value;
canvas.drawRect(
Rect.fromLTWH(x, 0, 4, size.height),
Paint()..color = Colors.red,
);
}
@override
bool shouldRepaint(SweepPainter oldDelegate) =>
oldDelegate.animation != animation;
}This pairs well with a RepaintBoundary. The sweep line repaints every frame, and the boundary keeps that work from touching the rest of the screen.
When a boundary helps
Add a RepaintBoundary when all of these are true:
- A region repaints frequently, such as an animation, a ticking timer, a video overlay or a drag handle.
- A neighboring region is expensive to paint, such as a large
CustomPaint, a chart with thousands of points, or many layered shadows. - The two regions do not need to repaint together.
Measure that the neighbor is repainting at all before you act. The usual evidence is a debugPrint count in its painter or a rainbow border that changes color every frame.
When a boundary hurts
A boundary is not free. Each one creates a separate layer, which costs memory and adds compositing work. Common mistakes:
- Boundaries everywhere. Wrapping every small widget produces many layers. The compositor has more to merge, and the savings per layer are tiny.
- A boundary around content that repaints every frame anyway. Wrapping the animating progress bar itself gains nothing for the bar. The useful boundary goes around the static neighbor.
- A boundary around cheap content. Painting a few rectangles is faster than managing a separate layer for them.
- Items inside a
ListView. The list already wraps each child. Adding another boundary doubles the layers.
The engine can also cache a boundary's content as a raster image when it sees the same layer painted several times without changes. This is a heuristic. You can hint at it with isComplexHint and willChangeHint on CustomPaint, but you cannot force it. Treat the gain as something you verify in the Performance view.
Choosing the right tool
| Symptom | Likely cause | First thing to try |
|---|---|---|
| Many widgets rebuild per frame, `build` is slow | Broad `setState` or inherited dependency | Narrow scope, `const`, selectors (earlier chapters) |
| Few rebuilds, but a static region keeps repainting | An animated sibling shares its layer | `RepaintBoundary` around the static region |
| Animation rebuilds a large subtree each tick | Animation drives `setState` | `AnimatedBuilder` with a `child`, or `repaint:` on the painter |
| Layout is slow after small changes | A change forces relayout up the tree | Fix constraints or use fixed sizes, not a boundary |
| Raster thread is slow, UI thread is fast | Heavy painting, `saveLayer`, large shadows or blurs | Simplify the effect, then consider boundaries |
A RepaintBoundary does not stop layout dirtiness from spreading. Layout has its own mechanism, relayout boundaries, and the framework sets those up automatically when a render object's size cannot affect its parent.
Adding this to the audit
Extend the rebuild audit from the previous chapters with one extra pass:
- Turn on repaint highlighting in DevTools in a debug build, or use the rainbow flag.
- Interact with the screen and note which regions flash when they should be still.
- For each flashing region, decide whether its content is expensive. Check the painter's
debugPrintcount or the raster time in profile mode. - Add a boundary only around expensive regions that repaint because of a neighbor.
- Re-measure in profile mode. If frame time did not improve, remove the boundary.
Exercise
A screen has a CircularProgressIndicator in a corner and a large CustomPaint chart in the middle, both children of the same Column inside the route. The widget rebuild count is zero after the first frame, yet the raster thread is slow and the chart's paint method logs on every frame. Explain why, and name the smallest change that stops the chart from repainting.
Show answer
The indicator's animation calls markNeedsPaint on its render object without any rebuild. That request walks up to the nearest repaint boundary, which is the route's layer, so every render object in that layer, including the chart, is painted again. shouldRepaint does not help because it is checked only when the painter is replaced, not when an ancestor layer repaints. Wrapping the CustomPaint chart in a RepaintBoundary gives it its own layer. The indicator's repaint request then stops at the route boundary, and the chart's layer is reused.
Exercise
You wrap each tile of a ListView.builder in your own RepaintBoundary to speed up scrolling, and memory use goes up with no frame-time improvement. Why?
Show answer
ListView.builder already wraps each child in a RepaintBoundary because addRepaintBoundaries defaults to true. The extra boundaries create a second layer per tile, which costs memory and compositing work without isolating anything new. Remove them, and add a boundary only inside a tile if a specific part of it repaints often while another part is expensive to paint.