Sub topic 17
Relayout and repaint boundaries
This chapter assumes you know the three trees (widget, element, render object) and the frame phases: build, layout, paint, composite. It also assumes you know that setState marks an element dirty. Here you will learn how Flutter stops layout and paint work from spreading beyond the part of the tree that changed.
Why boundaries exist
A render object that changes cannot just redo its own work. Its size may affect its parent's size, and its pixels share a layer with its neighbours. Without limits, one small change could force the whole tree to be laid out and painted again.
Flutter uses two kinds of boundary to cap that spread:
- A relayout boundary stops a layout invalidation from travelling further up the tree.
- A repaint boundary gives a subtree its own layer, so a repaint inside it does not repaint anything outside it, and the reverse.
The two are independent. A render object can be one, both, or neither.
Relayout boundaries
When a render object calls markNeedsLayout, Flutter checks whether it is a relayout boundary. If it is not, the parent is marked as needing layout too, and the check repeats up the tree. The walk ends at a boundary, which is added to the pipeline owner's list of nodes to lay out in the next frame.
You do not choose a relayout boundary directly. Flutter decides during layout. For a RenderBox, a child becomes a relayout boundary when any of these is true:
- The parent does not use the child's size (
parentUsesSizeisfalse). - The child's size depends only on its constraints (
sizedByParentistrue). - The constraints are tight, meaning the minimum and maximum are equal in both dimensions.
- The parent is not a render object, which is the case for the root.
Tight constraints are the case you will meet most often. SizedBox(width: 120, height: 40, child: ...) passes tight constraints to its child. The child can change however it likes, and its ancestors never need to hear about it.
Compare this with a Text placed directly in a Column. The Column uses the child's size to place its siblings, so parentUsesSize is true and the constraints are loose. A text change marks the Column dirty as well, and the walk continues up until it reaches a boundary.
Repaint boundaries
Painting works the same way. When a render object calls markNeedsPaint, Flutter walks up to the nearest ancestor whose isRepaintBoundary is true. That ancestor repaints, and so does every descendant that shares its layer. A descendant that is itself a repaint boundary and is not dirty reuses its existing layer.
The RepaintBoundary widget creates a RenderRepaintBoundary, which draws into its own layer. Some framework widgets already add boundaries. For example, ListView wraps each built item in one by default (addRepaintBoundaries is true), and page routes get one as well. You usually add RepaintBoundary yourself only around something that repaints often next to something expensive that does not.
The next example puts a spinning square next to a static painter that logs each time it paints.
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
class CountingPainter extends CustomPainter {
CountingPainter(this.name);
final String name;
@override
void paint(Canvas canvas, Size size) {
debugPrint('paint $name');
canvas.drawRect(
Offset.zero & size,
Paint()..color = const Color(0xFF2196F3),
);
}
@override
bool shouldRepaint(CountingPainter oldDelegate) => false;
}
class BoundaryDemo extends StatefulWidget {
const BoundaryDemo({super.key});
@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();
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
width: 100,
height: 100,
child: CustomPaint(painter: CountingPainter('static')),
),
RepaintBoundary(
child: RotationTransition(
turns: _controller,
child: SizedBox(
width: 100,
height: 100,
child: CustomPaint(painter: CountingPainter('spinner')),
),
),
),
],
);
}
}
void main() => runApp(
const Directionality(
textDirection: TextDirection.ltr,
child: BoundaryDemo(),
),
);Run this and watch the console. paint spinner prints on every frame, but paint static prints only at start-up. The animation calls markNeedsPaint on the rotating render object, and the walk stops at the RepaintBoundary. Remove the RepaintBoundary and both lines print every frame, because the rotation now dirties the root layer that both painters share.
Comparing the two boundaries
| Row | Relayout boundary | Repaint boundary |
|---|---|---|
| Created by | Flutter, during layout, from the rules above | You, with `RepaintBoundary`, or a framework widget |
| Stops | `markNeedsLayout` propagation upward | `markNeedsPaint` propagation upward |
| Cost | None | A separate layer, with extra memory |
| Visible in code | Only through tight constraints or `parentUsesSize` | `isRepaintBoundary` is `true` |
Seeing repaints
Set debugRepaintRainbowEnabled = true; (from package:flutter/rendering.dart) before runApp. Flutter then draws a changing coloured border over each repaint-boundary layer every time it repaints. In DevTools, the Highlight repaints option in the Flutter Inspector does the same. A border that flickers constantly around something that never changes is a sign that it is sharing a layer with something that does.
Failure modes and trade-offs
- Boundaries are not free. Each one allocates a layer and may keep a rasterized copy in memory. Wrapping every widget makes memory use and compositing work worse, not better.
- A boundary around content that always changes gains nothing. If the whole subtree repaints every frame, the layer is just overhead.
- Loose constraints can defeat relayout boundaries. A child that sizes itself to its content inside a parent that reads that size will pass layout dirtiness upward. Giving the child a fixed size, where the design allows it, turns it into a boundary.
- Measure first. Use the performance overlay or DevTools to find which phase is slow. Add a
RepaintBoundaryonly where the repaint highlight shows wasted painting.
Exercise
A Text sits directly inside SizedBox(width: 200, height: 50), inside a Column. The text string changes and its size changes. Does the Column need to be laid out again, and does the Text need a RepaintBoundary to avoid repainting the Column's other children?
Show answer
The Column does not need layout. SizedBox passes tight constraints, so the text's render object is a relayout boundary and the invalidation stops there. Painting is separate: without a RepaintBoundary, the text's markNeedsPaint walks up to the nearest repaint boundary, so the Column's other children in the same layer repaint too. A RepaintBoundary around the text would prevent that, but it is worth adding only if profiling shows the repaint is costly.