Sub topic 9
Tracking memory use and leaks
This chapter assumes you can build and run a Flutter app and understand StatefulWidget, asynchronous Dart code, and the widget tree. You will use the DevTools Memory view to distinguish normal memory changes from objects that remain reachable after they should be gone.
What the Memory view shows
Memory problems usually appear in one of two ways:
- The app uses more memory than expected during normal work.
- Memory continues to grow after the app repeats an action, such as opening and closing a screen.
Dart uses a garbage collector (GC). The garbage collector finds objects that the running program can no longer reach and reclaims their Dart heap memory. An object that is still referenced cannot be collected, even if the screen that created it is no longer visible.
Open DevTools while the app is running and select Memory. The chart shows memory categories such as Dart heap usage, external memory, and the amount of memory used by the Flutter engine. Use the controls to trigger garbage collection, take a heap snapshot, or start an allocation profile.
| Tool | Use it to answer |
|---|---|
| Memory chart | Is memory rising during a user action? |
| Heap snapshot | Which classes are present right now? |
| Allocation profile | Which classes were allocated during a time period? |
| External memory data | Is native or image memory contributing to usage? |
A rising chart is not automatically a leak. The runtime may reserve memory for later use. Compare the app after the same action has been repeated and after garbage collection has run.
Find objects that survive a screen
Use this repeatable test:
- Open the screen that might leak.
- Take a snapshot before the action.
- Close the screen.
- Force garbage collection.
- Take another snapshot.
- Repeat the open-and-close cycle several times.
- Compare instance counts for the screen, its state object, controllers, subscriptions, and models.
If the count grows after every cycle, inspect what still references those objects. A retained path in the snapshot can show the chain of references from a live root to the object. Common causes include a global collection, a service singleton, a callback list, a stream subscription, or a timer.
A State object should normally become unreachable when its widget is removed. Controllers and subscriptions often need explicit cleanup.
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(),
);
}
}AnimationController owns a ticker that produces animation frames. Calling dispose releases that ticker when the state is removed. The same principle applies to TextEditingController, ScrollController, FocusNode, Timer, stream subscriptions, and listeners registered with other objects.
Interpret allocation profiles
A heap snapshot describes retained objects at one moment. An allocation profile focuses on objects created during a selected interval. Start recording, perform one controlled action, stop recording, and inspect classes with high allocation counts.
High allocation is not necessarily a leak. A list view may create many short-lived objects while scrolling. The important question is whether those objects disappear after garbage collection. Compare:
- Allocated objects: everything created during the interval.
- Live objects: objects still present after collection.
- Retained size: memory held by an object and objects reachable only through it.
Check image-heavy screens separately. Decoded images can consume external memory even when Dart objects appear small. Reduce image dimensions, avoid keeping unnecessary image references, and measure again on a realistic device.
Verify the fix
After changing cleanup code, repeat the same test. The screen and its associated objects should stop accumulating across cycles. Also verify that the screen still works after returning to it. A premature dispose or canceled subscription can remove a leak while introducing missing updates or runtime errors.
Exercise
Exercise
After opening and closing a screen five times, its State objects keep increasing in a heap snapshot. What should you inspect first?
Show answer
Inspect retaining paths for the State objects, then check that the screen disposes its controllers and cancels subscriptions or timers. Repeat the test after the fix and confirm that live instance counts stop growing.