Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add onDispose to game.dart called from game_widget.dart #2659

Merged
merged 9 commits into from
Aug 20, 2023
4 changes: 4 additions & 0 deletions packages/flame/lib/src/game/game.dart
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,10 @@ abstract mixin class Game {
/// do cleanups to avoid memory leaks.
void onRemove() {}

/// Called when the game has been removed from the Flutter widget tree when
/// it was disposed by Flutter.
munsterlander marked this conversation as resolved.
Show resolved Hide resolved
void onDispose() {}

/// Called after the game has left the widget tree.
/// This can be overridden to add logic that requires the game
/// not be on the flutter widget tree anymore.
Expand Down
7 changes: 5 additions & 2 deletions packages/flame/lib/src/game/game_widget/game_widget.dart
Original file line number Diff line number Diff line change
Expand Up @@ -254,8 +254,11 @@ class GameWidgetState<T extends Game> extends State<GameWidget<T>> {
_loaderFuture = null;
}

void disposeCurrentGame() {
void disposeCurrentGame({bool isDispose = false}) {
spydon marked this conversation as resolved.
Show resolved Hide resolved
currentGame.removeGameStateListener(_onGameStateChange);
if (isDispose) {
currentGame.onDispose();
}
}

@override
Expand All @@ -281,7 +284,7 @@ class GameWidgetState<T extends Game> extends State<GameWidget<T>> {
@override
void dispose() {
super.dispose();
disposeCurrentGame();
disposeCurrentGame(isDispose: true);
// If we received a focus node from the user, they are responsible
// for disposing it
if (widget.focusNode == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,12 @@ class _MyGame extends FlameGame {
super.onRemove();
events.add('onRemove');
}

@override
void onDispose() {
super.onDispose();
events.add('onDispose');
}
}

class _TitlePage extends StatelessWidget {
Expand Down Expand Up @@ -185,6 +191,11 @@ void main() {
true,
reason: 'onRemove was not called',
);
expect(
events.contains('onDispose'),
true,
reason: 'onDispose was not called',
);
});

testWidgets('on resize, parents are kept', (tester) async {
Expand Down Expand Up @@ -229,6 +240,7 @@ void main() {
'onLoad',
'onMount',
'onRemove',
'onDispose',
'onGameResize',
'onMount',
],
Expand Down