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;
}
}
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.