Memory and Leaks
Memory that rises and falls is normal. Act on memory that only rises, or that stays high after the screen that used it is gone.
Gate: is there evidence?
- Profile mode on a physical device, DevTools Memory view. Open and close the suspect screen several times, trigger garbage collection with the GC button, and watch the baseline. A baseline that steps up after each round trip is a leak; a sawtooth that returns to baseline is not.
- Take a snapshot before and after the round trips and diff them. Look for classes whose instance count grows with each trip (a State class, a controller, a listener closure).
- For one growing instance, open its retaining path to see what still holds it. Fix the holder, not the instance.
No growth means no leak. Record it as "acceptable" in the audit and stop.
Usual holders
Check these in the code behind the growing class:
| Holder |
Fix |
AnimationController, TextEditingController, ScrollController, PageController, FocusNode, TabController created in State |
Call dispose() in State.dispose(); create once in initState, not in build() |
StreamSubscription, Timer |
cancel() in dispose() (or in a Bloc/Cubit close()) |
addListener on a ChangeNotifier, ValueNotifier or Listenable |
Matching removeListener, or use a builder widget that manages it |
| Anonymous closures passed to long-lived objects (singletons, services, global streams) |
Keep a reference and remove it, or stop the long-lived object holding UI callbacks |
BuildContext or State kept in a service, static field or long async chain |
Pass plain data instead; after an await, check mounted before using context (the use_build_context_synchronously lint finds these) |
| Provider/Riverpod state kept alive after its screen is gone |
Use the existing auto-dispose or scoped mechanism for screen-scoped state; keep keepAlive only where re-creation is genuinely costly |
| Caches (in-memory maps, repositories) |
Give each a size cap and an eviction rule; see the cache rules in flutter-perf-derived-state |
imageCache |
It has configurable limits (maximumSize, maximumSizeBytes). Lower them only if the snapshot shows image data dominating; image decode size is in flutter-perf-images-and-assets |
A controller that is created and disposed in the same State is correct; do not add dispose() calls to objects you did not create.
Automated check
Where the project's Flutter version supports leak tracking in widget tests, add it for the affected screen so the leak cannot return. Check the current Flutter and leak_tracker documentation for the exact setup; it has changed between versions. If it is not available, write a test that pushes and pops the screen and asserts the controller or subscription is released through a fake.
Do not
- Do not call
dispose() twice or on shared objects.
- Do not clear caches on a timer to hide growth; find the holder.
- Do not add a package for leak detection when DevTools and the lint are enough.
Verify
Repeat the same round trips on the same device after the fix. Report the baseline before and after, and the instance counts from the snapshot diff. Method: flutter-perf-profiling-and-validation.
Hard rules
- Act only on what the user asked. Before answering or changing anything, open the relevant files and check what is already done; report only what you checked, never guess, and do not redo finished work. Reason: guesses and repeated work waste the user's credit.
1---2name: flutter-perf-memory-and-leaks3description: >4 Use when memory climbs during normal use, the app is killed on low-memory5 devices, or a screen keeps working after it was closed. Investigates and fixes6 Flutter memory growth and leaks: undisposed controllers, focus nodes, timers and7 stream subscriptions, listeners never removed, BuildContext captured by async8 work or long-lived objects, unbounded image or data caches, and state that9 outlives its screen. Uses DevTools memory snapshots and leak tracking. Do not10 use for slow frames (flutter-perf-build-and-rebuild) or image decode size11 (flutter-perf-images-and-assets).12metadata:13 source: https://skillmd.com/skills/kinwisenz-devops/flutter-perf-memory-and-leaks14---1516# Memory and Leaks1718Memory that rises and falls is normal. Act on memory that only rises, or that stays high after the screen that used it is gone.1920## Gate: is there evidence?21221. Profile mode on a physical device, DevTools Memory view. Open and close the suspect screen several times, trigger garbage collection with the GC button, and watch the baseline. A baseline that steps up after each round trip is a leak; a sawtooth that returns to baseline is not.232. Take a snapshot before and after the round trips and diff them. Look for classes whose instance count grows with each trip (a State class, a controller, a listener closure).243. For one growing instance, open its retaining path to see what still holds it. Fix the holder, not the instance.2526No growth means no leak. Record it as "acceptable" in the audit and stop.2728## Usual holders2930Check these in the code behind the growing class:3132| Holder | Fix |33|---|---|34| `AnimationController`, `TextEditingController`, `ScrollController`, `PageController`, `FocusNode`, `TabController` created in `State` | Call `dispose()` in `State.dispose()`; create once in `initState`, not in `build()` |35| `StreamSubscription`, `Timer` | `cancel()` in `dispose()` (or in a Bloc/Cubit `close()`) |36| `addListener` on a `ChangeNotifier`, `ValueNotifier` or `Listenable` | Matching `removeListener`, or use a builder widget that manages it |37| Anonymous closures passed to long-lived objects (singletons, services, global streams) | Keep a reference and remove it, or stop the long-lived object holding UI callbacks |38| `BuildContext` or `State` kept in a service, static field or long async chain | Pass plain data instead; after an `await`, check `mounted` before using `context` (the `use_build_context_synchronously` lint finds these) |39| Provider/Riverpod state kept alive after its screen is gone | Use the existing auto-dispose or scoped mechanism for screen-scoped state; keep `keepAlive` only where re-creation is genuinely costly |40| Caches (in-memory maps, repositories) | Give each a size cap and an eviction rule; see the cache rules in [flutter-perf-derived-state](../flutter-perf-derived-state/SKILL.md) |41| `imageCache` | It has configurable limits (`maximumSize`, `maximumSizeBytes`). Lower them only if the snapshot shows image data dominating; image decode size is in [flutter-perf-images-and-assets](../flutter-perf-images-and-assets/SKILL.md) |4243A controller that is created and disposed in the same `State` is correct; do not add `dispose()` calls to objects you did not create.4445## Automated check4647Where the project's Flutter version supports leak tracking in widget tests, add it for the affected screen so the leak cannot return. Check the current Flutter and `leak_tracker` documentation for the exact setup; it has changed between versions. If it is not available, write a test that pushes and pops the screen and asserts the controller or subscription is released through a fake.4849## Do not5051- Do not call `dispose()` twice or on shared objects.52- Do not clear caches on a timer to hide growth; find the holder.53- Do not add a package for leak detection when DevTools and the lint are enough.5455## Verify5657Repeat the same round trips on the same device after the fix. Report the baseline before and after, and the instance counts from the snapshot diff. Method: [flutter-perf-profiling-and-validation](../flutter-perf-profiling-and-validation/SKILL.md).5859## Hard rules6061- Act only on what the user asked. Before answering or changing anything, open the relevant files and check what is already done; report only what you checked, never guess, and do not redo finished work. Reason: guesses and repeated work waste the user's credit.