Sub topic 6
Telling UI-thread jank from raster-thread jank
This chapter assumes you can already run an app in profile mode, open the DevTools Performance view, and read the frames chart. You should also know what a build method does. Here you learn to decide, for a single slow frame, which thread caused the problem. That decision tells you which tool to open next and which kind of fix to try.
Why the split matters
Flutter builds each frame in two stages that run on two threads.
- The UI thread runs your Dart code. It handles build, layout, and paint, and it produces a layer tree. The layer tree is a description of what to draw, not pixels.
- The raster thread takes the layer tree and turns it into GPU commands, then submits them. It runs engine code (Skia or Impeller), not your Dart code.
The frames chart draws every frame as two bars, one for each thread. A frame is janky when either bar takes longer than the frame budget (about 16.7 ms at 60 Hz, 8.3 ms at 120 Hz). The two bars point at different problems:
| Slow bar | What it means | Typical cause | Where to look |
|---|---|---|---|
| UI | Your Dart code did too much work | Heavy `build()`, synchronous parsing, big loops, deep rebuilds | Timeline Events, enhanced tracing |
| Raster | The scene was expensive to draw | Offscreen layers, large images, many clips, shaders | Frame Analysis, then widget choices |
| Both | Two problems, or one problem feeding the other | Huge rebuild that also creates a complex scene | Fix the UI side first, then re-measure |
Because the stages are pipelined, the raster thread can still be drawing frame N while the UI thread starts frame N+1. A slow raster stage therefore delays presentation even when your Dart code finishes quickly. The reverse also holds: a fast raster stage cannot rescue a UI thread that missed its deadline.
Step 1: read the two bars
In the Performance view, each frame in the chart has a UI bar and a raster bar. Click a janky frame and compare the two durations shown in the frame details.
- Find the frames that DevTools marks as over budget. These stand out from the normal frames.
- Select one and read the UI and raster times.
- Compare each time with the budget for your device's refresh rate, not a fixed 16 ms.
- Note which bar is over. If only one is, you have your answer. If both are, pick the larger overrun and start there.
Do not judge from a single frame. One slow frame at app start or on first navigation is common, because the app is loading code, decoding images, and warming caches. Look for a pattern: the same interaction producing slow frames each time you repeat it.
Step 2: a UI-thread example
The JankyText widget from the earlier setup does a large loop inside build():
import 'package:flutter/material.dart';
int slowSum() {
var total = 0;
for (var i = 0; i < 50000000; i++) {
total += i % 7;
}
return total;
}
class JankyText extends StatelessWidget {
const JankyText({super.key});
@override
Widget build(BuildContext context) {
// Expensive work inside build() runs on the UI thread on every rebuild.
return Text('Result: ${slowSum()}');
}
}When this widget rebuilds, the UI bar for that frame is long and the raster bar stays short. The scene is just one line of text, so there is almost nothing for the raster thread to draw. That combination (long UI, short raster) is the signature of UI-thread jank.
Open the Timeline Events tab for the frame. You should see the UI thread's Build work dominating, with your function's time sitting inside it. The fix is to move the computation off the UI thread and out of build(), as the FixedText version does with Isolate.run.
Step 3: a raster-thread example
Now consider a screen where the Dart code is cheap but the scene is expensive:
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: Scaffold(body: HeavyList())));
}
class HeavyList extends StatelessWidget {
const HeavyList({super.key});
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: 200,
itemBuilder: (context, index) {
// Opacity and a save-layer clip both force offscreen rendering.
return Opacity(
opacity: 0.9,
child: ClipRRect(
borderRadius: BorderRadius.circular(24),
clipBehavior: Clip.antiAliasWithSaveLayer,
child: Container(
height: 120,
margin: const EdgeInsets.all(8),
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [Colors.indigo, Colors.teal],
),
),
),
),
);
},
);
}
}Scroll this list in profile mode on a real device. The build() method does very little work, so the UI bar stays low. The raster bar grows, because each row asks the engine to render into an offscreen buffer (a "save layer") and then composite it back. That is a costly operation, especially when many rows are visible and the list scrolls every frame. The signature here is the reverse of the first example: short UI, long raster.
Step 4: confirm with Frame Analysis
The frames chart tells you which thread is slow. The Frame Analysis tab tells you what DevTools thinks is likely responsible. Select the janky frame and open Frame Analysis. Depending on your DevTools version, it can report items such as:
- Which of the UI and raster phases took the most time.
- Whether the frame includes expensive operations, such as save layers or shader compilation.
- Whether images in the frame were much larger than the area they were drawn into.
Treat these as hints. They narrow the search but do not replace reading the timeline. If Frame Analysis points at a raster cost and the Timeline Events tab shows a long UI phase too, you have two things to fix.
Step 5: apply the matching fix
Pick the fix from the thread, not from habit.
For UI-thread jank:
- Move expensive computation out of
build(). UseIsolate.runfor pure CPU work and start it once, for example ininitStateor alate finalfield. - Rebuild less. Split large widgets so a state change rebuilds only the small part that depends on it. Use
constconstructors where possible. - Avoid doing synchronous parsing or file work in response to scroll or animation ticks.
For raster-thread jank:
- Remove avoidable offscreen layers. Replace
Opacitywith a color that has alpha, or useAnimatedOpacityorFadeTransitionfor animations. Keep clips onClip.hardEdgeor the defaultClip.antiAliasunless you truly need save-layer behavior. - Decode images near their display size. A 4000-pixel photo shown in a 100-pixel thumbnail wastes memory and raster time. Use
cacheWidthorcacheHeightonImagewidgets, or serve smaller files. - Isolate frequently repainting areas with
RepaintBoundary, so an animation does not force the rest of the scene to be redrawn. Test this, because extra boundaries add their own cost.
A lighter version of the earlier list avoids the save layers:
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: Scaffold(body: LightList())));
}
class LightList extends StatelessWidget {
const LightList({super.key});
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: 200,
itemBuilder: (context, index) {
// Alpha is baked into the colors and the rounding is part of the
// decoration, so no offscreen layer is needed.
return Container(
height: 120,
margin: const EdgeInsets.all(8),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(24),
gradient: LinearGradient(
colors: [
Colors.indigo.withOpacity(0.9),
Colors.teal.withOpacity(0.9),
],
),
),
);
},
);
}
}After the change, run the same scroll gesture again and compare the raster bars. The change is only proven if the numbers drop.
Edge cases and common mistakes
- First-run spikes. The first time a screen or animation runs, raster time can spike because of shader compilation on Skia. These spikes appear on first use and disappear on repeat. Impeller, the newer renderer, precompiles its shaders, which removes most of this class of jank. A later chapter covers it in detail. For now, repeat the interaction before concluding a raster problem is permanent.
- UI work that causes raster work. A rebuild that adds hundreds of widgets also grows the layer tree, so both bars can rise together. Reduce the rebuild first, then re-measure the raster bar.
- Raster jank that Dart cannot fix directly. You cannot optimize the engine's code. You can only give it a cheaper scene. If the raster bar is high, change what you draw, not how your Dart code is written.
- Wrong refresh rate. On a 120 Hz device, a 12 ms frame is over budget even though it would pass at 60 Hz. Check which budget DevTools applies to your device.
- Tracing overhead. The enhance-tracing options add timeline events and can slightly slow the UI thread. Turn them on when you need detail and off when you want clean timings.
A quick decision procedure
- Reproduce the jank in profile mode on a physical device.
- Select a janky frame and compare the UI and raster bars against the budget.
- If UI is over, go to Timeline Events and find the longest Dart work.
- If raster is over, go to Frame Analysis and look at layers, images, and clips.
- If both are over, fix UI first and re-measure.
- Change one thing, repeat the same gesture, and compare.
Exercise
You scroll a list in profile mode on a physical phone. In the frames chart, the slow frames show a UI bar of 4 ms and a raster bar of 22 ms on a 60 Hz display. Which thread is causing the jank, and name two changes you could try first?
Show answer
The raster thread, since 22 ms exceeds the 16.7 ms budget while the 4 ms UI time is well within it. The Dart code is cheap, so the scene is expensive to draw. Two things to try: remove offscreen layers by replacing Opacity or Clip.antiAliasWithSaveLayer with colors that include alpha or Clip.antiAlias, and decode large images near their display size with cacheWidth or cacheHeight. Re-run the same scroll and compare the raster bars afterwards.
Exercise
A widget calls a function that loops 50 million times inside build(). The UI bar is 90 ms and the raster bar is 3 ms. Why won't optimizing images or clips help, and what change addresses the problem?
Show answer
The raster thread is not the bottleneck, so reducing raster work does nothing for the 90 ms UI bar. The cost is Dart code running on the UI thread in every build. Move the computation out of build() and run it once off the UI thread, for example with Isolate.run stored in a late final field of a State object, and show the result with a FutureBuilder.