With Flutter 2.2, DevTools’ memory management view has received a major update that makes memory debugging easier. I’ll show you how to use DevTools to detect memory leaks. See the official documentation for more information.

Detecting memory leaks

The preparatory work

  1. After running the app in Profile mode, open DevTools and switch to the Memory TAB, as shown below.

  1. Open the Settings and check the Enable Advanced Memory Settings option. The GC button will appear on the page for manually triggering GC, as shown in the following figure.

  1. Click Take Heap Snapshot to obtain the memory Snapshot, as shown in the following figure. The green box indicates the memory Snapshot.

  1. Click the memory snapshot and select the package name for your project, for example my project name is BASIC. As shown in the figure below, the memory object corresponding to the current snapshot of package will appear in the green box. By looking at these objects, we can determine whether memory has been properly reclaimed.

detection

  1. To simulate a memory leak, I will open itTestPageAnd open one of themTimer.
late Timer _timer; @override void initState() { super.initState(); _timer = Timer.periodic(Duration(seconds: 1), (timer) { print('timer is running... '); }); } // @override // void dispose() { // super.dispose(); // _timer.cancel(); / /}Copy the code

Open TestPage and click to take a memory snapshot, as shown below. TestPage appears in the list.

  1. exitTestPage, manually triggers the GC to retrieve the snapshot again, at which point, as we expect, due toTimerNot manually invokedcancel()Method has caused a memory leak,TestPageIt will not be recycled properly and will still appear in the list. As shown in the figure below

  1. Repair memory leaks and restore_timer.cancel()
late Timer _timer; @override void initState() { super.initState(); _timer = Timer.periodic(Duration(seconds: 1), (timer) { print('timer is running... '); }); } @override void dispose() { super.dispose(); _timer.cancel(); }Copy the code

Perform the above steps again, and you will find that the TestPage has disappeared from the list and has been collected normally.