Sub topic 14
Painting and the layer tree
This chapter assumes you know that a render object has a layout phase and a paint phase, and that markNeedsPaint schedules a frame. It also assumes you can read a short RenderBox subclass. The chapter covers what the paint phase produces, why Flutter keeps a separate layer tree, and how repaint boundaries limit the work.
What the paint phase produces
Paint does not draw pixels. It records drawing commands. During the paint phase, each render object's paint method issues calls on a Canvas, such as drawRect or drawParagraph. That canvas writes into a picture recorder. The result is a display list, which Flutter stores in a PictureLayer. Later, the engine rasterizes the display lists on the raster thread.
So the paint phase has two outputs:
- Display lists, which describe shapes, text, and images.
- A tree of layers, which groups those display lists and the effects applied to them.
Painting order and offsets
The paint phase starts at the root RenderView. Each render object paints itself first, then its children, in order. This gives the familiar back-to-front order: later siblings cover earlier ones.
A render object never knows its own position on screen. Layout stored each child's position relative to its parent, in the child's parentData. The parent adds that value to its own offset argument and passes the sum down:
import 'package:flutter/rendering.dart';
class RenderTwoBoxes extends RenderBox
with
ContainerRenderObjectMixin<RenderBox, ContainerBoxParentData<RenderBox>>,
RenderBoxContainerDefaultsMixin<RenderBox,
ContainerBoxParentData<RenderBox>> {
@override
void setupParentData(RenderBox child) {
if (child.parentData is! ContainerBoxParentData<RenderBox>) {
child.parentData = ContainerBoxParentData<RenderBox>();
}
}
@override
void performLayout() {
double x = 0;
double height = 0;
RenderBox? child = firstChild;
while (child != null) {
child.layout(const BoxConstraints(), parentUsesSize: true);
final data = child.parentData! as ContainerBoxParentData<RenderBox>;
data.offset = Offset(x, 0);
x += child.size.width;
if (child.size.height > height) height = child.size.height;
child = data.nextSibling;
}
size = constraints.constrain(Size(x, height));
}
@override
void paint(PaintingContext context, Offset offset) {
defaultPaint(context, offset);
}
@override
bool hitTestChildren(BoxHitTestResult result, {required Offset position}) {
return defaultHitTestChildren(result, position: position);
}
}defaultPaint loops over the children and calls context.paintChild(child, data.offset + offset) for each one. Always paint a child through context.paintChild, never by calling child.paint directly. paintChild is where Flutter checks whether the child is a repaint boundary, as described below.
From render objects to layers
Most render objects add no layer of their own. A RenderPadding or a RenderParagraph draws into whatever PictureLayer is currently recording. Flutter creates a new layer only when a render object needs one. There are three common reasons:
- It applies an effect that the engine must handle as a unit, such as opacity, a clip, a transform, or a backdrop filter.
PaintingContexthas methods for these:pushOpacity,pushClipRect,pushTransform, and others. Each one inserts a layer such asOpacityLayer,ClipRectLayer, orTransformLayer, and paints the child beneath it. - It is a repaint boundary, so it gets its own
OffsetLayer. - It draws something the engine composes separately, such as a platform view or a texture.
When a layer subtree interrupts a picture, Flutter ends the current PictureLayer and starts a new one afterward. The paint order stays correct because the layer tree keeps the same order.
RenderPadding has no layer. It only adjusts the offset it passes to its child, and the paragraph draws into the picture beneath the opacity layer.
Repaint boundaries
Without boundaries, one markNeedsPaint would repaint a large part of the tree. A render object marks itself dirty and asks its parent to do the same, all the way up, because a parent's picture may contain the child's drawing. The walk stops at the nearest ancestor whose isRepaintBoundary is true. That boundary repaints, and everything above it is untouched.
At the boundary, paintChild makes a choice. If the child is a repaint boundary and is not dirty, Flutter reuses its existing layer and skips its paint call. If it is dirty, Flutter repaints it into its own OffsetLayer. A parent can repaint, and its picture can change, while a clean boundary child is carried over as it was.
RepaintBoundary is the widget that sets this flag. Scrollables and many framework widgets already include one, so check before adding more.
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
class LayerDemo extends StatelessWidget {
const LayerDemo({super.key});
@override
Widget build(BuildContext context) {
return const Directionality(
textDirection: TextDirection.ltr,
child: RepaintBoundary(
child: Opacity(
opacity: 0.5,
child: Padding(
padding: EdgeInsets.all(16),
child: Text('Hello'),
),
),
),
);
}
}
void main() {
runApp(const LayerDemo());
WidgetsBinding.instance.addPostFrameCallback((_) {
debugDumpLayerTree();
});
}In a debug build, debugDumpLayerTree prints the root OffsetLayer, the boundary's OffsetLayer, an OpacityLayer, and a PictureLayer with the drawing. The exact text varies between Flutter versions.
Compositing and the final scene
After paint, RenderView.compositeFrame walks the layer tree. It adds each layer to a SceneBuilder, builds a Scene, and calls render on the window. The engine then rasterizes it on the raster thread. Compositing is cheap compared with painting because it only assembles existing layers. When only a boundary's position or opacity changes, Flutter can update that layer without re-recording its picture.
Costs and failure modes
- Too many boundaries. Each boundary creates a layer, and the engine may cache its raster output. Boundaries around tiny widgets cost memory and compositing work, and they save nothing.
- Too few boundaries. An animation inside a large static screen repaints the whole screen each frame.
- Expensive effects. Widgets such as
Opacitywith a fractional value,ClipRRectwith anti-aliasing, andBackdropFiltercan force offscreen rendering. PreferAnimatedOpacityorFadeTransitionfor animation, since the latter does not rebuild its child. - Mutating during paint. Never change layout-affecting state or call
markNeedsLayoutinsidepaint. Paint must read state and draw. UsemarkNeedsPaintin setters, asRenderColoredSquaredoes in the chapter on custom render objects.
Exercise
A CustomPaint animates at 60 frames per second inside a screen that contains a long static list. You wrap the CustomPaint in a RepaintBoundary. Which render objects repaint on each frame, and which ones are reused?
Show answer
The animated CustomPaint calls markNeedsPaint. The dirty mark travels up only to the nearest repaint boundary, the new RenderRepaintBoundary. That boundary repaints into its own layer. The static list and the rest of the screen are not dirty, so their layers are reused and their paint methods are not called. The compositor reassembles the layer tree into a new scene.