Sub topic 1
How Flutter produces a frame
A Flutter frame is one complete pass from "something changed" to "new pixels on screen". The DevTools Performance view shows the cost of each stage of that pass. You can only read it if you know the stages and which thread runs each one. This chapter builds that model. Later chapters use it to read the frames chart and fix slow frames.
Prerequisites
This chapter assumes you can do the following:
- Build and run a basic Flutter app with
flutter run. - Write
StatelessWidgetandStatefulWidgetclasses and explain whatbuild()returns. - Use
setStateand read simple Dart (futures, callbacks, classes). - Use a working Flutter SDK with a device or emulator.
You do not need DevTools experience. You do not need to know the rendering internals either, because this chapter covers them.
The threads involved
A Flutter app runs on several threads. Two of them determine how a frame is measured.
| Thread | Runs | Typical work |
|---|---|---|
| UI thread | Your Dart code and the framework | Animation ticks, `build()`, layout, paint (recording drawing commands), event handlers |
| Raster thread | The engine's rendering backend | Turning recorded drawing commands into GPU work and pixels |
| Platform thread | The host OS main thread | Plugin calls, platform views, OS events |
| IO threads | Engine helpers | Image decoding, asset loading |
The UI thread and the raster thread are the pair you will see in the frames chart. Each frame needs time on both. They work as a pipeline. While the raster thread draws frame N, the UI thread can already be preparing frame N+1.
The UI thread is the Dart isolate's main thread. Anything slow in your Dart code blocks it, including your own build() methods, JSON parsing, and loops. The raster thread never runs your Dart code. It only runs engine code, so you affect it indirectly through what you ask the engine to draw.
What triggers a frame
Flutter does not redraw continuously. It draws a frame when something requests one:
- A call to
setStateor another change that marks an element dirty. - A running animation, where a
Tickerasks for the next frame. - A scroll or touch event that changes what is visible.
- A window resize or a change in device metrics.
When nothing changes, no frames are produced and the app uses almost no CPU. This is why an idle app shows an empty frames chart.
A request does not run immediately. The framework calls scheduleFrame(), which asks the engine for the next vsync signal. Vsync is the display's refresh tick, for example every 16.7 ms on a 60 Hz display. At that tick the engine calls back into Dart, and the UI thread starts a frame.
The phases of a frame on the UI thread
When the engine signals that a frame should begin, the framework runs these phases in order.
- Animation (transient callbacks). Tickers and animation controllers advance to the current frame time. Their listeners fire, and those listeners often call
setState. - Microtasks. Dart runs any microtasks queued by the animation callbacks.
- Build. Dirty elements rebuild. Each dirty widget's
build()runs, and the framework compares the new widget tree to the old one. Only elements marked dirty rebuild, which is whysetStateplacement matters. - Layout. Render objects receive constraints from their parents and report sizes back. Render objects that were marked as needing layout are laid out.
- Compositing bits and paint. Render objects record drawing commands (rectangles, text, images, clips) into layers. This builds a layer tree. Painting does not touch pixels. It records what to draw.
- Compositing. The layer tree is turned into a scene and handed to the engine.
- Semantics. If accessibility is active, the semantics tree is updated.
- Post-frame callbacks. Callbacks registered with
addPostFrameCallbackrun after the frame is submitted.
Build, layout, and paint together are sometimes called the "draw frame" part of the work. They are the main cost in most UI-thread-bound frames.
Hand-off to the raster thread
After compositing, the UI thread submits the scene to the engine and is free again. The raster thread then takes the layer tree and:
- Walks the layers and issues the drawing commands to the graphics backend.
- Runs clipping, blending, opacity, and shadow work on the GPU.
- Presents the finished image for the display.
Newer Flutter versions use Impeller as the default backend on iOS and on current Android devices. Skia is the older backend. Either way the raster thread's job is the same. Which backend you have affects how shader work is handled, which a later chapter covers.
This split explains a basic diagnostic rule. If the UI thread is slow, your Dart code (build, layout, paint recording) is doing too much. If the raster thread is slow, the scene is expensive to draw. Examples are many layers, large blurs, or heavy clipping.
Seeing the phases in code
The following program logs each phase as it happens. It uses a Ticker for the animation phase, a CustomPaint painter for the paint phase, and a post-frame callback. Run it with flutter run and watch the console.
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
void main() => runApp(const MaterialApp(home: FramePhases()));
class FramePhases extends StatefulWidget {
const FramePhases({super.key});
@override
State<FramePhases> createState() => _FramePhasesState();
}
class _FramePhasesState extends State<FramePhases>
with SingleTickerProviderStateMixin {
late final Ticker _ticker;
int _ticks = 0;
@override
void initState() {
super.initState();
_ticker = createTicker((elapsed) {
debugPrint('1 animation callback at $elapsed');
setState(() => _ticks++);
if (_ticks >= 3) {
_ticker.stop();
}
})..start();
}
@override
void dispose() {
_ticker.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
debugPrint('2 build (tick $_ticks)');
WidgetsBinding.instance.addPostFrameCallback((_) {
debugPrint('4 post-frame callback (tick $_ticks)');
});
return Scaffold(
body: Center(
child: CustomPaint(
size: const Size(200, 200),
painter: _LoggingPainter(_ticks),
),
),
);
}
}
class _LoggingPainter extends CustomPainter {
_LoggingPainter(this.tick);
final int tick;
@override
void paint(Canvas canvas, Size size) {
debugPrint('3 paint (tick $tick)');
canvas.drawRect(
Offset.zero & size,
Paint()..color = Colors.indigo.withValues(alpha: 0.3 + 0.2 * tick),
);
}
@override
bool shouldRepaint(_LoggingPainter old) => old.tick != tick;
}For each tick you should see the lines in the order 1, 2, 3, 4. Layout has no log line here because it runs between build and paint without user code. The order is the point of the example. Animation comes first, then build, then paint, then post-frame work.
The setState call in the ticker callback is safe because it happens in the animation phase, before build. Calling setState during build() itself is an error, because the framework is already building.
Why the pipeline matters for performance
Three consequences follow directly from the model.
Work in build() is paid every rebuild. build() can run many times per second during an animation. Anything expensive inside it repeats on every frame. The JankyText example in a later chapter shows this.
One slow phase delays the whole frame. The phases run one after another on one thread. A slow build() pushes layout and paint later, and the frame can miss its vsync deadline even if layout and paint are cheap.
Fast UI and slow raster still produce a slow frame. The thread that is not busy tells you nothing about the frame's total time. A frame is on screen only after both threads finish with it. That is why the Performance view reports the two durations separately.
Common misunderstandings
- "setState redraws the screen immediately." It only marks the element dirty and schedules a frame. The rebuild happens at the next vsync.
- "Paint draws pixels." Paint records commands. The raster thread draws pixels.
- "The raster thread runs my widgets." It never runs Dart. A widget's cost lands on the raster thread only through the drawing commands it produces.
- "If the UI thread looks fine, the app is fine." A frame can be slow on the raster thread alone.
- "Every rebuild repaints everything." Flutter uses repaint boundaries to limit repainting, and unchanged subtrees can reuse their layers. The cost depends on what is marked dirty.
Summary of the model
Keep this chain in mind for the rest of the tutorial:
- Something requests a frame, and the framework waits for vsync.
- The UI thread runs animation, build, layout, and paint. This is your Dart code and the framework.
- The UI thread hands the layer tree to the engine.
- The raster thread turns the layer tree into pixels on the GPU.
- A frame reaches the display only after both threads finish their share.
Exercise
A screen's build() method calls a function that takes 40 ms of CPU time, and the screen has a running animation. Which thread is the likely bottleneck, and in which phase of the frame does the cost fall?
Show answer
The UI thread is the bottleneck. The cost falls in the build phase, because build() runs there. It repeats on every animation frame, and the 40 ms delays layout and paint for that frame as well. The raster thread is not affected directly.
Exercise
Put these frame steps in the order they happen: raster thread draws the layer tree, build, animation callbacks, paint, layout, post-frame callbacks.
Show answer
Animation callbacks, build, layout, paint, post-frame callbacks (the UI thread side), with the raster thread drawing the layer tree after paint and compositing hand the scene to the engine. The post-frame callbacks run on the UI thread once the frame is submitted, so they can run while the raster thread is still working.