skip to Main Content

Will this code cause a memory leak in Flutter?

Classes A and B reference each other:

The VM in Flutter has GC, which is different from other languages ​​I’ve learned, such as OC or Swift.
I observed through dev tools and found that it seemed to be GC, but I’m not familiar with dev tools and I’m not sure if what I observed is correct.

Another question is: will this code cause memory leaks in dart cli?

Thanks!

class A {
  late B b;
}

class B {
  final A a;
  B({required this.a});
}

class MyWidget extends StatelessWidget {
  const MyWidget({super.key});

  @override
  Widget build(BuildContext context) {
    return TextButton(
        onPressed: () {
          _onClickTest();
        },
        child: const Text('Test'));
  }

  void _onClickTest() {
    final a = A();
    final b = B(a: a);
    a.b = b;
  }
}

2

Answers


  1. Based on your code, no, it should not cause a memory leak in either Flutter or Dart CLI. Dart’s garbage collector is designed to handle circular references effectively.

    In your code, the a and b instances are created inside the _onClickTest method. They will be reachable only within the scope of this method. After the method execution completes and there are no other references to these instances, they become eligible for garbage collection.

    Login or Signup to reply.
  2. Memory leaks are a common error in programming, especially when using languages that have no built in automatic garbage collection, such as C and C++. Wikipedia

    It rarely happens when using a language that support garbage collection, fortunately dart does.

    all reference variables which are declared within your code a , b are created if and only if the button is pressed, once the button is pressed the callback method is called and those references are created.

    Once the method is finished this allocated space in memory is freed up by unreferencing a and b, it’s the garbage collector responsibility.

    So no, your code will not consume or abuse the memory which leads to any memory leak.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search