Sub topic 12
One frame: build, layout, paint, composite
This chapter assumes you know the widget, element, and render object trees from the earlier chapters. It also assumes you can read setState code and know what a RenderBox is. Here we follow the work Flutter does between "something became dirty" and "pixels reach the screen".
From dirty to scheduled
Flutter does not rebuild continuously. Nothing runs until something asks for a frame. setState calls Element.markNeedsBuild, which adds the element to the BuildOwner's dirty list. The BuildOwner calls onBuildScheduled, which ends in SchedulerBinding.scheduleFrame. That call asks the engine for a vsync signal, the display's "start the next frame" pulse. If no vsync arrives, nothing happens. Many setState calls before the next vsync still produce one frame.
When the signal arrives, the engine calls two entry points in order:
handleBeginFrameruns transient callbacks. Tickers, and so animations, live here. A ticker may callsetState, so this step can add more dirty elements.handleDrawFrameruns persistent callbacks. The most important one isRendererBinding.drawFrame. Then it runs post-frame callbacks.
The phases inside drawFrame
drawFrame has a fixed order. Each phase finishes before the next one starts.
| Phase | Entry point | Works on | Output |
|---|---|---|---|
| Build | `BuildOwner.buildScope` | Dirty elements | Updated element and render object trees |
| Layout | `PipelineOwner.flushLayout` | Render objects marked for layout | Sizes and offsets |
| Compositing bits | `PipelineOwner.flushCompositingBits` | Render objects whose layer needs changed | Flags used by paint |
| Paint | `PipelineOwner.flushPaint` | Render objects marked for paint | Layers holding recorded drawing commands |
| Composite | `RenderView.compositeFrame` | The layer tree | A `Scene` sent to the engine |
After composite, Flutter runs flushSemantics when accessibility is active. Finally BuildOwner.finalizeTree unmounts elements that were deactivated during the frame and not reinserted.
Build
Dirty elements are sorted by depth, so parents rebuild before children. This matters because a parent's rebuild can update a child element with a new widget. That child is then rebuilt as part of the same pass, and the work is not repeated. If an element becomes dirty while the build phase runs, buildScope inserts it into the sorted list and keeps going.
Build ends by calling updateRenderObject on the render objects whose widgets changed. Setters on the render object call markNeedsLayout or markNeedsPaint only when a value actually changed, as in RenderColoredSquare from the earlier chapter. A rebuild that produces equal values therefore costs little downstream.
Layout
flushLayout visits render objects marked dirty, again sorted by depth. Each one runs performLayout, passes constraints to its children, and reads back their sizes. A relayout boundary stops the dirty mark from climbing, so Flutter relays out only the subtree below it. The next chapter covers these boundaries.
One exception is that some widgets build during layout. LayoutBuilder and SliverList need their constraints before they know which children exist. They call back into the build machinery from inside layout, which is why they can create children lazily.
Paint
flushPaint walks dirty render objects deepest first. Each paint call draws into a canvas that records commands. A repaint boundary gets its own layer, so its recorded commands can be reused when nothing inside it changed.
Composite
The layers form a tree. compositeFrame flattens it into a Scene and hands the scene to the engine. All of this has run on the UI thread. The raster thread then turns the scene into GPU work. A frame can therefore be slow on either thread, and the two are measured separately.
Observing frames in code
The timing callback reports build and raster durations for each frame. Run this and tap or hot-reload to produce frames.
import 'package:flutter/scheduler.dart';
import 'package:flutter/widgets.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
SchedulerBinding.instance.addTimingsCallback((List<FrameTiming> timings) {
for (final t in timings) {
debugPrint(
'build ${t.buildDuration.inMicroseconds} us, '
'raster ${t.rasterDuration.inMicroseconds} us, '
'total ${t.totalSpan.inMicroseconds} us',
);
}
});
runApp(const Directionality(
textDirection: TextDirection.ltr,
child: Text('Hello'),
));
}Timings arrive in batches, shortly after frames finish, not once per frame in real time. Use them for trends. Use DevTools for single-frame detail.
Ordering rules and edge cases
- Calling
setStateinsidebuildthrows, because the element is mid-build and marking it dirty again would loop. Calling it from a post-frame callback is allowed and schedules a new frame. - A post-frame callback runs once, after the frame it was registered for, and does not schedule a frame itself. Call
SchedulerBinding.instance.scheduleFrame()if you need one. - Marking a render object for layout during paint is an error. Layout results must be final before paint begins.
- If only paint is dirty, as with a color change, the layout phase has no work and is skipped.
- A frame that does nothing visible still costs the build pass over every dirty element, so unnecessary
setStatecalls cost time even when the pixels do not change.
Reading the pipeline when debugging
Use the phase to decide where to look. If build durations are high, a widget's build method does too much or rebuilds too many descendants. If layout dominates, intrinsic sizing or deep dirty chains are likely causes. High raster time often points to expensive layers, such as saveLayer from opacity, clipping, or shadows. The Performance view in DevTools shows UI and raster threads as separate bars. Compare them before you change code.
Exercise
A widget animates the color property of a RenderColoredSquare with a ticker. Which phases of each frame do real work, and which are skipped?
Show answer
The ticker runs in handleBeginFrame and calls setState. The build phase rebuilds the widget and calls updateRenderObject. The color setter calls markNeedsPaint only, so flushLayout has no work. Paint and composite run, because the layer changed. The size setter is not touched, so layout is skipped.
Exercise
Two setState calls happen in the same event handler, and a third happens 5 ms later, still before the next vsync. How many frames are built, and why?
Show answer
One frame. The first setState schedules a frame, and the later calls only mark elements dirty, because the frame is already scheduled. All dirty elements are built together when the vsync arrives.