Sub topic 11
Measuring performance with traceAction
This chapter assumes you can write and run an integration test, use finders and pumpAndSettle, and run flutter drive with a test driver. Here you will record a performance timeline while a test performs a user interaction, then save and read the result.
Why measure performance in an integration test
A widget test runs in a simulated environment. It has no real GPU, no real rasterizer, and no real frame deadlines. It cannot tell you whether a list scrolls smoothly on a mid-range phone.
An integration test runs your real app on a real device. That makes it a good place to measure things users feel:
- Dropped frames while scrolling a long list.
- Slow first frames when a screen opens.
- Jank during an animated transition.
The integration_test package provides traceAction on the test binding. It wraps a block of test code and records a timeline of what the Flutter engine did while that block ran.
What traceAction does
traceAction is a method of IntegrationTestWidgetsFlutterBinding. You pass it an async callback that performs the interaction you want to measure. Internally it:
- Starts recording a timeline through the VM service.
- Runs your callback.
- Stops recording and collects the timeline events.
- Stores the result in the binding under a report key.
The report key is a string you choose, such as scrolling_timeline. Under flutter drive, the driver script receives the stored data and can write it to a file. Only the code inside the callback is measured, so keep setup such as launching the app and navigating to the screen outside it.
Writing a traced test
The following test launches the app, finds the first scrollable, flings it, and records the work under the key scrolling_timeline.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:my_app/main.dart' as app;
void main() {
final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets('scrolling performance', (tester) async {
app.main();
await tester.pumpAndSettle();
final list = find.byType(Scrollable).first;
await binding.traceAction(() async {
await tester.fling(list, const Offset(0, -500), 10000);
await tester.pumpAndSettle();
}, reportKey: 'scrolling_timeline');
});
}Points to notice:
ensureInitialized()returns the binding, and you keep it in a variable. You need that variable to calltraceAction.flingtakes the finder, an offset, and a velocity in logical pixels per second. A negativedymoves the content up, as a finger swiping upward does.pumpAndSettlestays inside the callback so the recording covers the whole scroll, including the deceleration.- The test has no
expect. Its purpose is to produce data. You can add assertions on widgets if you also want to check behavior.
The driver script
The timeline only reaches a file when you run through flutter drive. The driver below receives the report data and saves it.
import 'package:flutter_driver/flutter_driver.dart' as driver;
import 'package:integration_test/integration_test_driver.dart';
Future<void> main() {
return integrationDriver(
responseDataCallback: (data) async {
if (data == null) return;
final timeline = driver.Timeline.fromJson(
data['scrolling_timeline'] as Map<String, dynamic>,
);
final summary = driver.TimelineSummary.summarize(timeline);
await summary.writeTimelineToFile(
'scrolling_timeline',
pretty: true,
includeSummary: true,
);
},
);
}The key 'scrolling_timeline' must match the reportKey in the test. flutter_driver is a separate SDK package, so add it to dev_dependencies for this driver to compile:
dev_dependencies:
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
flutter_driver:
sdk: flutterSave the driver as test_driver/integration_test.dart. The plain integrationDriver() call without a callback still runs the test and reports pass or fail, but it does not write timeline files.
Running with flutter drive and profile mode
Run the test through the driver and choose the build mode on purpose:
flutter drive \
--driver=test_driver/integration_test.dart \
--target=integration_test/app_test.dart \
--profile \
-d <device_id>The --profile flag matters. Debug builds include assertions and run unoptimized code, so their frame times say little about what users get. Release builds remove the instrumentation the timeline needs. Profile mode is optimized and keeps tracing available, so it is the standard choice for performance runs.
Reading the output
After the run, the driver writes files into a build directory in your project. With the key above, you get:
build/scrolling_timeline.timeline.json: the raw timeline events. You can load it in Chrome atchrome://tracingor in Perfetto to inspect each frame.build/scrolling_timeline.timeline_summary.json: a summary produced becauseincludeSummaryis true.
The summary contains fields such as these:
| Field | Meaning |
|---|---|
| `average_frame_build_time_millis` | Mean time the UI thread spent building frames |
| `worst_frame_build_time_millis` | Slowest single UI-thread frame |
| `average_frame_rasterizer_time_millis` | Mean time the raster thread spent drawing frames |
| `worst_frame_rasterizer_time_millis` | Slowest single raster-thread frame |
| `missed_frame_build_budget_count` | Frames whose build exceeded the frame budget |
| `missed_frame_rasterizer_budget_count` | Frames whose raster work exceeded the budget |
| `frame_count` | Number of frames recorded |
The frame budget is about 16.7 ms on a 60 Hz display and about 8.3 ms on a 120 Hz display. A frame that takes longer misses its slot, and the user sees a stutter. The build thread and raster thread work in a pipeline, so check both. A slow build time points to expensive widget build methods or layout. A slow raster time points to costly painting such as large shadows, clipping, or saveLayer calls.
Turning numbers into a check
The summary files are useful for humans. For automation, you can fail the run when a threshold is crossed. Inside responseDataCallback, read the summary and throw if a limit is exceeded:
import 'package:flutter_driver/flutter_driver.dart' as driver;
import 'package:integration_test/integration_test_driver.dart';
Future<void> main() {
return integrationDriver(
responseDataCallback: (data) async {
if (data == null) return;
final timeline = driver.Timeline.fromJson(
data['scrolling_timeline'] as Map<String, dynamic>,
);
final summary = driver.TimelineSummary.summarize(timeline);
await summary.writeTimelineToFile(
'scrolling_timeline',
pretty: true,
includeSummary: true,
);
final worst = summary.summaryJson['worst_frame_build_time_millis'];
if (worst is num && worst > 40) {
throw StateError('Worst build frame took $worst ms');
}
},
);
}Choose thresholds from your own baseline, not from a universal number. Performance varies by device, so a limit tuned on one phone may fail on another.
Edge cases and common errors
- No timeline file appears. You probably ran
flutter testinstead offlutter drive, or the driver uses plainintegrationDriver()without a callback. The data needs the driver to write it. - A
nullor missing key. The string indata['...']must equal thereportKey. A typo gives a null lookup and a cast error. - Results change between runs. Frame times are noisy. Run the interaction several times, compare medians or the worst case across runs, and keep the device plugged in, cool, and with the screen on. Close other apps and disable battery saver.
- Startup work pollutes the numbers. If you begin recording before the app has settled, the first-frame work and image decoding appear in your data. Call
pumpAndSettlebeforetraceAction. For a fair comparison of scrolling, consider scrolling once before the recorded run so caches are warm, or deliberately keep the cold run if that is what you want to measure. - A hanging test.
pumpAndSettlewaits until no frames are scheduled. An infinite animation, such as a progress indicator that spins forever, keeps scheduling frames, so it never settles and the call times out. Usepumpwith a duration inside the callback in that case. - Web targets. Frame timeline data on web has different tooling, and results are not comparable to mobile. Treat web performance runs separately.
Beyond a single scroll
traceAction works with any interaction, so you can measure other flows by changing the callback:
await binding.traceAction(() async {
await tester.tap(find.byKey(const Key('open_details')));
await tester.pumpAndSettle();
}, reportKey: 'navigation_timeline');Each call needs a distinct reportKey. The binding keeps one report per key, and reusing a key in the same run overwrites the earlier data. If you record several traces in one test file, remember to handle each key in the driver callback.
Where this fits in a workflow
Performance tracing complements functional tests. A reasonable routine is:
- Keep functional integration tests running on every change, using
flutter test. - Run the traced tests with
flutter drive --profileon a fixed reference device, on a schedule or before releases. - Store the summary JSON from each run and compare it with the previous one to catch regressions.
Because device performance varies, comparing the same device across time is more reliable than comparing different devices.
Exercise
You run a test that calls binding.traceAction(..., reportKey: 'listscroll') using `flutter test integrationtest/apptest.dart -d <deviceid>`. The test passes, but no timeline files appear in the build directory. Give two changes that would make the files appear, and name the build mode you should use for the measurement.
Show answer
First, run the test through flutter drive with --driver=test_driver/integration_test.dart and --target=integration_test/app_test.dart, because the driver is what receives the report data. Second, make the driver call integrationDriver with a responseDataCallback that reads data['list_scroll'], builds a TimelineSummary, and calls writeTimelineToFile. The key must match the reportKey exactly. Use profile mode (--profile) on a real device for the measurement.
Exercise
A traced scroll shows worst_frame_rasterizer_time_millis of 45 ms but a low worst_frame_build_time_millis. Which thread is the likely bottleneck, and what kinds of causes would you look for?
Show answer
The raster thread is the bottleneck. Look for costly painting work such as large or layered shadows, clipping with anti-aliasing, saveLayer calls from opacity or similar effects, and large images that need scaling or decoding. Slow widget builds are unlikely because the build time is low.