Sub topic 3
Finding expensive code with the CPU Profiler
This chapter assumes you know Dart async code, can write StatefulWidget classes, can run an app on a device, and have DevTools open from the earlier chapters.
Profiling CPU work
Run the app in profile mode so timings reflect release-like performance:
flutter run --profileOpen the CPU Profiler tab, start recording, perform the slow action, and stop. Use the bottom-up view to see which functions consumed the most time.
To label your own work, wrap it in Timeline.timeSync so it appears as a named block:
import 'dart:developer';
int sumOfSquares(List<int> values) {
return Timeline.timeSync('sumOfSquares', () {
var total = 0;
for (final v in values) {
total += v * v;
}
return total;
});
}Tracking memory use and leaks
A leak is an object that stays in memory after nothing uses it. The Memory view shows instance counts. If a screen's objects keep growing after you leave it, look for resources you never disposed. A common mistake is skipping dispose() for an AnimationController:
import 'package:flutter/material.dart';
class Pulse extends StatefulWidget {
const Pulse({super.key});
@override
State<Pulse> createState() => _PulseState();
}
class _PulseState extends State<Pulse> with SingleTickerProviderStateMixin {
late final AnimationController _controller =
AnimationController(vsync: this, duration: const Duration(seconds: 1))
..repeat();
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return FadeTransition(opacity: _controller, child: const FlutterLogo());
}
}Inspecting HTTP traffic with the Network view
The Network view lists each request with its status code, duration, and response size. Check status codes first. A slow screen can also be a repeated request that should be cached.
| Symptom | Tool to open first |
|---|---|
| Dropped frames | Performance |
| Slow Dart code | CPU Profiler |
| Growing memory | Memory |
| Slow or failed requests | Network |
| Large download | App Size |
Measuring build size with the App Size tool
Build with the size analysis flag:
flutter build apk --analyze-sizeThen load the generated JSON file in the App Size tab. It shows which packages take the most space.
A repeatable workflow from symptom to verified fix
flowchart TD- Reproduce the symptom in profile mode and record a baseline number.
- Pick the tool from the table above.
- Change one thing.
- Repeat the same steps and compare the numbers with the baseline.
Only keep a fix when the measured number improves.
Exercise
Why does the CPU Profiler need a named timeline block for sumOfSquares?
Show answer
The named block makes that function easy to find in the recording, instead of hunting through unnamed framework calls.
Exercise
A screen's memory grows each time it opens and closes. Which fix is most likely needed?
Show answer
Call dispose() on every controller and resource the state created, such as the AnimationController in the Pulse example.