Home:ALL Converter>Flutter Memory Leak with push/pop

Flutter Memory Leak with push/pop

Ask Time:2021-03-31T07:17:04         Author:pascalbros

Json Formatter

I really don't get the Dart Garbage Collector.

Let's setup a simple Widget like this:

import 'package:flutter/material.dart';
import 'SecondModule.dart';

class First extends StatefulWidget {
  @override
  FirstState createState() => FirstState();
}

class FirstState extends State<First> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        toolbarHeight: 60,
        title: Text("First"),
      ),
      body: SafeArea(
        child: Center(child:
        OutlinedButton(onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (context) => Second())),
            child: Text("Go to second screen")))
      ),
    );
  }
}

And basically the second widget is the same, but pushing on the first. When I try to push multiple times, let's say 6 times, the allocations list shows:

  • 3 First/FirstState
  • 3 Second/SecondState

Now let's go ahead:

  • Popping to the first screen, it still shows 3 First, 3 Second.
  • Pushing 12 times, it shows 6 First, 6 Second.
  • Popping to the first, it shows random number of instances, something between 3-6 across multiple app run.
  • If I call the Garbage Collector, using the button in DevTools, after it shows 1 First/1 Second correctly.

Am I doing something wrong or Dart Memory Management is supposed to work like this? How can I remove the Widget from memory on pop?

Thanks a lot, cheers.

Author:pascalbros,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/66879649/flutter-memory-leak-with-push-pop
yy