When the FlameGame gets disposed (page closes), it should remove all components of itself (call onRemove()
on all the sub-components to let them clear their resources)
First of all, when we close the game page (which contains a game), it does not automatically call remove on the child objects, to do that we need to write the below code manually:
@override
void onRemove() {
removeAll(children);
super.onRemove();
}
This onRemove()
method on the game that extends FlameGame
gets called when the page closes, but when we call removeAll(children);
, it adds the components to the lifecycle._removals
queue. But it never processes this queue. Because GameWidget is removed from the widget tree and there is no other tick to call lifecycle.processQueues()
.
So it leads to a memory leak in some components such as FlameBlocListenable
because onRemove
will never be called and subscription leaks.
I expect that FlameGame call removeAll(children);
under the hood and process the removal queue before the game disposes to allow all sub-components to free their resources in the onRemove()
function.
I wanted to put a Zapp link, but it seems Zapp is down at this moment, so there is a main.dart file here.
You just need to add these dependencies to run the reproducible code:
flame_bloc: ^1.8.2
flutter_bloc: ^8.1.2
flame: 1.6.0
Steps:
HomePage
opensPlay
button on the HomePage, then GamePage
opens.LeakingCounterComponent.onNewState(1)
prints in the screenMyGame.onRemove()
is called, but LeakingCounterComponent.onRemove()
didn't call, so it leaked through it's subscription.Play
and plus
button againLeakingCounterComponent.onNewState(2)
printed 2 times (because there is a leak)Play
and plus
button againLeakingCounterComponent.onNewState(3)
printed 3 times (because there are two leaks)As a workaround, I wrote the below code:
@override
void onRemove() {
...
removeAll(children);
processPendingLifecycleEvents();
super.onRemove();
}
So with this code, LeakingCounterComponent.onRemove()
gets called everytime we close the game page
Doctor summary (to see all details, run flutter doctor -v):
[β] Flutter (Channel stable, 3.7.1, on macOS 13.2.1 22D68 darwin-arm64, locale
en-US)
[β] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
[β] Xcode - develop for iOS and macOS (Xcode 14.1)
[β] Chrome - develop for the web
[β] Android Studio (version 2021.3)
[β] IntelliJ IDEA Community Edition (version 2022.2.4)
[β] IntelliJ IDEA Community Edition (version 2022.3.1)
[β] IntelliJ IDEA Community Edition (version 2022.3.2)
[β] VS Code (version 1.76.0)
[β] Connected device (2 available)
[β] HTTP Host Availability
β’ No issues found!
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too