Sub topic 3
Fixing Common Causes of Slow Frames
This chapter assumes you can profile an app in profile mode and read the frames chart in DevTools. You should also know the difference between UI-thread and raster-thread work.
Fixing common causes of slow frames
The most common cause of jank is expensive work inside build(), which runs on the UI thread on every rebuild. Move that work out of build() and run it once. Here, Isolate.run moves the computation to a separate isolate, so the UI thread stays free.
import 'dart:isolate';
import 'package:flutter/material.dart';
int slowSum() {
var total = 0;
for (var i = 0; i < 50000000; i++) {
total += i % 7;
}
return total;
}
class FixedText extends StatefulWidget {
const FixedText({super.key});
@override
State<FixedText> createState() => _FixedTextState();
}
class _FixedTextState extends State<FixedText> {
late final Future<int> _result = Isolate.run(slowSum);
@override
Widget build(BuildContext context) {
return FutureBuilder<int>(
future: _result,
builder: (context, snapshot) {
if (!snapshot.hasData) {
return const CircularProgressIndicator();
}
return Text('Result: ${snapshot.data}');
},
);
}
}Enhancing traces with build, layout, and paint tracking
The enhance tracing options in the Performance view add timeline events for each widget build, layout, and paint. They make traces more detailed but add overhead, so turn them on only for diagnosis. Enable them in DevTools, or set the framework flags in code during a profile run:
import 'package:flutter/foundation.dart';
void enableTracing() {
debugProfileBuildsEnabled = true;
debugProfileLayoutsEnabled = true;
debugProfilePaintsEnabled = true;
}Adding your own timeline events
Timeline.timeSync wraps a block of work in a named event. The event then appears by name in the Timeline Events tab.
import 'dart:developer';
List<String> parseCatalog(String raw) {
return Timeline.timeSync('parse_catalog', () {
return raw.split('\n').where((line) => line.isNotEmpty).toList();
});
}Shader compilation jank and Impeller
The first time an animation uses a new effect, Flutter compiles a shader on the raster thread. That compile can freeze several frames. Impeller, Flutter's newer rendering engine, precompiles most shaders when the app is built, which avoids most of this jank. If you still see shader jank, check whether the app uses Impeller on your target platform.
A repeatable measure, change, re-measure workflow
Change one thing at a time, and record the frame times before and after each change.
Exercise
The FixedText example still shows a spinner for about a second on launch. Why is that expected, and what would you check first if the spinner lasted much longer?
Show answer
The computation runs off the UI thread, so the spinner shows until the isolate returns. Check whether slowSum is doing more work than expected, and confirm the frames chart shows the UI thread staying under the frame budget while the spinner runs.