Sub topic 9
Tracking memory use and leaks
This chapter assumes you can run a Flutter app, connect DevTools to it, and read the difference between debug, profile, and release mode. It also assumes you know the State lifecycle, including initState and dispose. If DevTools is not yet connected, go back to the launch chapter first.
Memory problems rarely crash an app right away. They show up as an app that slows down after twenty minutes, a list that stutters after many scrolls, or an out-of-memory kill on a low-end phone. The Memory view in DevTools shows what the Dart VM has allocated, what the garbage collector can free, and what is stuck.
How Dart memory works, briefly
Dart allocates objects on a managed heap. The garbage collector (GC) frees an object when nothing reachable from a root still refers to it. Roots include static fields, the running call stack, and active timers, streams, and tickers.
A memory leak in Dart is therefore not "forgotten to call free". A leak is an object that your program no longer needs but that is still reachable. Something still holds a reference, so the GC may not collect it.
Two terms matter when you read the Memory view:
- Shallow size is the memory taken by the object itself.
- Retained size is the memory that would be freed if the object were collected. It includes everything only that object keeps alive.
A small widget state can have a large retained size if it references a big image or a large list.
Pick the right run mode
Memory numbers in debug mode are inflated by debugging support. Use profile mode for measurements you plan to compare or trust.
# Run the app in profile mode on a connected device
flutter run --profile
# Start DevTools on its own, then connect using the VM service URI printed by flutter run
dart devtoolsUse a real device when you can. Emulators and simulators share the host's memory behavior and can hide or exaggerate problems.
A tour of the Memory view
Open DevTools and select Memory. The view has several parts, and the exact tab names change between Flutter versions, so treat the labels below as a guide.
- The chart plots memory over time. It separates categories such as Dart heap, native memory, and the resident set size reported by the operating system. Events such as GC runs and snapshots appear on the timeline.
- Profile Memory (called the Trace or Profile tab in some versions) lists classes with their instance counts and sizes. You can sort by count or by size.
- Diff Snapshots lets you take a snapshot of the heap at one moment, take another later, and compare the two.
- Trace Instances lets you pick a class and record where in code its instances are created.
The chart gives you the symptom. The snapshot tools give you the cause.
Reading the chart
Memory use normally rises as you use the app and drops when the GC runs. This creates a sawtooth pattern. A healthy app has a sawtooth whose lows stay roughly level.
A leak looks different. The lows climb steadily, and each GC frees less than the one before.
Not every rise is a leak. Caches, decoded images, and lazily loaded data legitimately use memory. The question is whether the growth stops when you stop repeating the action. A cache that plateaus is fine. Growth with no limit is the problem.
Finding a leak with snapshot diffs
The most reliable technique is to compare snapshots before and after repeating one action. Follow these steps.
- Run the app in profile mode and open the Memory view.
- Navigate to a stable starting screen, such as the home screen.
- Click the garbage can icon (Run GC) to collect garbage, then take a snapshot. This is your baseline.
- Perform the suspect action several times. For example, open a detail screen and go back, ten times.
- Return to the same starting screen, run GC again, and take a second snapshot.
- Select the second snapshot and choose to diff it against the first.
The diff lists classes whose instance counts grew. Sort by the count delta. If _PulseState or AnimationController shows ten new instances after ten visits, you have found the pattern: one leaked instance per visit.
Run GC before each snapshot. Otherwise you will see uncollected but unreachable garbage, which looks like a leak and is not.
Select a leaked class and inspect its retaining path. The path shows the chain of references from a root to the object. Read it from the root down. The link you own, such as a timer callback, a stream subscription, or a listener list, is usually the one you need to cut.
A common leak: undisposed controllers
Objects that register with the framework, such as AnimationController, TextEditingController, ScrollController, FocusNode, and StreamSubscription, must be released in dispose. An AnimationController registers a ticker that the scheduler keeps calling. If the widget is removed without disposing the controller, the ticker and everything it references stay reachable.
This version releases the controller correctly:
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() {
// Omitting this line leaves the controller and its ticker alive after the widget is removed.
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return FadeTransition(opacity: _controller, child: const FlutterLogo());
}
}If you delete the _controller.dispose() line and repeat the open-and-close test, the diff shows _PulseState and AnimationController instance counts rising with each visit. Restore the line and the counts return to baseline after GC. That before-and-after comparison is your verification.
In debug mode, Flutter often reports an undisposed ticker with an assertion when the widget is removed. Profile and release builds strip these checks, which is another reason to rely on snapshots for real measurement.
Other common causes
| Cause | Why it holds memory | Fix |
|---|---|---|
| Undisposed controller or focus node | The scheduler or a listener list keeps a reference | Call `dispose()` in `State.dispose` |
| Uncancelled `StreamSubscription` | The stream holds the listener closure, which captures the state | Call `cancel()` in `dispose` |
| Active `Timer.periodic` | The timer is a root and its callback captures `this` | Call `cancel()` in `dispose` |
| Listener added and never removed | The notifier's list holds your callback | Call `removeListener` in `dispose` |
| Static or global collection that only grows | Static fields are roots | Bound the size, or remove entries |
| Large images decoded at full size | Decoded bitmaps use width × height × 4 bytes | Use `cacheWidth`, `cacheHeight`, or resized assets |
| Closures capturing a `BuildContext` | The context keeps its element and ancestors alive | Avoid storing contexts beyond the widget's life |
The image case is not a leak in the strict sense. The memory is in use on purpose, but it can still trigger out-of-memory kills. A 4000 × 3000 photo decodes to about 48 MB (4000 × 3000 × 4 bytes) regardless of its file size on disk.
Tracing where objects are allocated
When the diff shows a class growing but you do not know which code creates it, use Trace Instances. Enable tracing for the class, repeat the action, and then inspect the allocation stack traces. This shows which call site created the instances, which is often enough to find the missing cleanup.
Tracing adds overhead, so enable it only for the classes you need and turn it off afterward.
Checking memory use of ordinary work
Not every memory problem is a leak. A function that builds a very large list temporarily will spike memory and then fall. The chart shows a tall peak, not a rising baseline. The fix is different: process data in chunks, stream it, or paginate it.
You can label your own work with the timeline and log markers so the spike lines up with an event you can recognize. The Logging view shows named messages that you can match against the chart:
import 'dart:developer' as developer;
void loadCart(List<String> items) {
developer.log(
'Loaded ${items.length} items',
name: 'cart',
);
}Read the log entry's timestamp, then look at the memory chart at that same moment.
Common mistakes
- Measuring in debug mode. The numbers are higher and noisier, and some behaviors differ.
- Skipping GC before a snapshot. Pending garbage appears as growth.
- Testing once. One extra instance can be a cache. Repeat the action five to ten times so a per-visit leak stands out from noise.
- Chasing the total. A flat total can hide a leak if another part of the app frees memory at the same time. Look at per-class counts.
- Fixing without re-measuring. After the change, repeat the same steps and confirm the instance counts stay flat.
- Ignoring native memory. Plugins, platform views, and image decoders allocate outside the Dart heap. If the Dart heap is flat but the resident set size grows, the cause may be native.
Exercises
Exercise
You open and close a detail screen 10 times in profile mode. After running GC and diffing snapshots, you see +10 instances of _DetailPageState and +10 of StreamSubscription. What is the most likely cause, and where do you look to fix it?
Show answer
Each visit leaves one state object alive, and the matching stream subscription suggests the state never cancels its subscription. The stream holds a listener closure that captures the state, so the state stays reachable. Check the retaining path to confirm, then call cancel() on the subscription in _DetailPageState.dispose. Repeat the same 10-visit test and confirm the counts return to baseline.
Exercise
The memory chart shows a tall peak when a screen loads and then falls back to its earlier level after GC. Is this a leak? What would you change?
Show answer
No. A leak shows a baseline that rises across repeated actions. A peak that falls back means the work uses a lot of memory temporarily, for example building a large list or decoding a large image. Reduce the peak by loading data in pages or chunks, or by decoding images at a smaller size with cacheWidth or cacheHeight.
Exercise
Why must you run GC before taking each snapshot when looking for leaks?
Show answer
Unreachable objects that have not yet been collected still count as instances. Without a GC, they appear as growth between snapshots and look like a leak. Running GC first leaves only objects that are still reachable, which are the real leak candidates.