Sub topic 10
Enhancing traces with build, layout, and paint tracking
By default, the Timeline Events tab shows a frame as a few coarse blocks. You can see that BUILD took 18 ms, but not which widget was responsible. The enhance-tracing options add one trace event per widget build, per layout, and per paint. This chapter covers what each option records, how to turn it on from DevTools or from code, how to read the added events, and what the extra detail costs.
Prerequisites
This chapter assumes you can do the following:
- Run an app in profile mode and open the DevTools Performance view.
- Select a frame in the Flutter frames chart.
- Open the Timeline Events tab.
- Tell UI-thread work from raster-thread work.
If a frame is slow on the UI thread and the coarse view doesn't show why, this chapter applies. If the raster thread is the slow one, these options won't help. They only add detail to UI-thread work.
What the default trace shows
For each frame, the UI thread runs a handful of framework phases. The default trace marks these phases, but not the individual widgets or render objects inside them.
| Phase | What happens | Default trace detail |
|---|---|---|
| Build | Widgets' `build` methods run and the element tree is updated | One `BUILD` block per frame |
| Layout | Render objects compute sizes and positions | One `LAYOUT` block per frame |
| Paint | Render objects record drawing commands | One `PAINT` block per frame |
A BUILD block of 18 ms tells you the build phase is slow. It doesn't tell you whether one widget did all the work or a thousand widgets each did a little. Enhanced tracing answers that question.
The three tracking options
Each option corresponds to a flag in the Flutter framework. When a flag is on, the framework wraps the matching work in a named timeline event.
| DevTools option | Framework flag | New events |
|---|---|---|
| Track widget builds | `debugProfileBuildsEnabled` | One event per widget whose `build` runs, named after the widget's type |
| Track layouts | `debugProfileLayoutsEnabled` | One event per render object that performs layout |
| Track paints | `debugProfilePaintsEnabled` | One event per render object that paints |
The exact label in DevTools can differ between versions. Recent versions put these toggles under an "Enhance tracing" menu on the Performance tab. Older versions listed them as separate "Trace widget builds", "Trace layouts", and "Trace paints" checkboxes. The behavior is the same.
Recent Flutter versions also have debugProfileBuildsEnabledUserWidgets. It limits build events to widgets you wrote and hides the framework's internal widgets, which makes the trace shorter. Check that your SDK version has it before relying on it.
Turning the options on
You have two ways to turn them on.
From DevTools
- Run the app in profile mode:
flutter run --profile -d <device-id>. - Open DevTools and go to the Performance tab.
- Open the Enhance tracing menu and tick the options you want.
- Reproduce the slow interaction in the app.
- Select a slow frame in the frames chart and open Timeline Events.
Toggling an option from DevTools changes the flag in the running app through a service extension. It applies to frames produced after the toggle. Frames already recorded keep their coarse detail, so reproduce the problem again after switching an option on.
From code
Setting the flags from code makes the setting survive hot restarts and applies from the first frame. This helps when the jank happens during startup, before you can click anything in DevTools.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
void main() {
// Adds timeline events for each widget build, layout, and paint.
// Same effect as the enhance-tracing toggles in DevTools; use in profile runs only.
debugProfileBuildsEnabled = true;
debugProfileLayoutsEnabled = true;
debugProfilePaintsEnabled = true;
runApp(const MaterialApp(home: Scaffold(body: Center(child: Text('Hello')))));
}Set the flags before runApp, so the first frame is already traced. Don't commit this to your production entry point. A flag you forgot to remove will slow every user's app and bloat every trace.
Reading the enhanced trace
Select a frame and look at the Timeline Events tab. The events are drawn as a flame chart. The horizontal axis is time and the vertical axis is nesting depth. A child event sits below its parent and fits inside its width.
With builds tracked, the BUILD block now has children. Each child is named after a widget, such as ListView, ProductCard, or JankyText. A child nested inside another one was built as part of its parent's build.
Finding the expensive widget
Use this procedure on a slow UI-thread frame:
- Find the widest phase block among
BUILD,LAYOUT, andPAINT. - Look at the events directly under it, and find the widest one.
- Click it to see its duration in the details pane.
- Descend into its children until the width drops sharply. The widget where the width is no longer explained by its children did the expensive work itself.
That last step is the key. A parent that is 40 ms wide with children that add up to 2 ms has spent 38 ms in its own code. Take the JankyText widget from the earlier chapters as an example:
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()}');
}
}With build tracking on, you would see a JankyText event that is wide, with only a thin Text event beneath it. The width belongs to JankyText itself, and that points at its build method.
Layout and paint events
Layout and paint events are named after render object types, such as RenderFlex, RenderParagraph, or RenderCustomPaint. A few patterns come up often:
- A wide
RenderParagraphlayout event. Text measurement is expensive, especially for long strings or many text spans. - Layout events repeated many times under one parent. Some container is laying out its children more than once, which can happen with intrinsic-size widgets such as
IntrinsicHeight. - A wide
RenderCustomPaintpaint event. YourCustomPainter.paintmethod is doing too much work per frame. - Many small paint events across a long list. Check whether the list builds more items than it needs to show.
Costs and pitfalls
Tracing is not free. Each event costs a small amount of time to create, and a frame with thousands of widgets creates thousands of events. Keep these points in mind.
- Timings are inflated. A frame that takes 12 ms normally might take 16 ms with all three options on. Use the enhanced trace to find where the time goes, not to decide whether you meet the budget.
- Compare like with like. Measure the before and after of a fix with the same tracing options on both times.
- Turn on only what you need. Start with build tracking for UI-thread jank. Add layout or paint tracking only when the build phase doesn't explain the frame. Fewer options means fewer events and less overhead.
- Event limits. The timeline buffer holds a limited number of events. With all options on, a long recording can push older frames out of the buffer. Record short sessions.
- Profile mode only. In debug mode the numbers are not representative, as covered earlier. These flags are for profile runs.
Combining with your own events
Enhanced tracing names the framework's work. For work that isn't a widget build, such as parsing a file or preparing data, add your own named event with Timeline.timeSync. It shows up in the same flame chart.
import 'dart:developer';
List<String> parseCatalog(String raw) {
return Timeline.timeSync('parse_catalog', () {
return raw.split('\n').where((line) => line.isNotEmpty).toList();
});
}If a build event is wide and has no children that explain it, wrapping the suspect calls inside build in Timeline.timeSync tells you which one is slow. The next chapter treats custom events in more detail.
Common mistakes
- Reading a trace taken before the toggle. Frames recorded before you enabled an option have no extra events. Reproduce the interaction again.
- Blaming the widest leaf. A leaf event can be wide because it was waiting on nothing but your code inside it, or because a parent rebuilt it hundreds of times. Count how often it appears as well as how wide it is.
- Using enhanced tracing on raster jank. If the raster thread is slow, build, layout, and paint events on the UI thread won't explain it. Go back to the frames chart and check which thread is over budget.
- Leaving the flags on after the fix. Turn the options off before the re-measure that confirms your result against the budget. Otherwise the overhead can hide the improvement you made.
Summary
Enhanced tracing turns the three coarse UI-thread phases into a flame chart of the widgets and render objects that took the time. You turn it on from the Enhance tracing menu or from the three debugProfile…Enabled flags. Read the trace by walking down from the widest phase to the widget whose width its children don't explain. Use only the options you need, compare traces taken with the same settings, and turn them off before final measurements.
Exercise
A UI-thread frame takes 30 ms. Build tracking shows a BUILD block of 25 ms. Under it, a ProductList event is 24 ms wide, and its only child, ListView, is 3 ms wide. Where did the time go, and what is your next step?
Show answer
About 21 ms was spent in ProductList's own code, because its width isn't explained by its child. Next, open its build method and look for expensive work such as parsing, sorting, or large loops. Wrap the suspect calls in Timeline.timeSync to find which one is slow, then move that work out of build (for example, into an isolate or a cached field). Finally, re-measure with the same tracing options.
Exercise
Why shouldn't you compare a frame time recorded with all three tracking options on against the 16 ms budget to decide whether your app meets it?
Show answer
Each tracking option adds a timeline event for every widget build, layout, or paint, and creating those events takes time. The frame is slower than it would be without tracing, so the number overstates the real cost. Use enhanced tracing to find where time goes, then turn it off to check the real frame time against the budget.