From 726cb8b6390c839f9cbab959b2268a7b45fa691c Mon Sep 17 00:00:00 2001 From: Luan Nico Date: Sat, 14 Dec 2024 17:20:56 -0500 Subject: [PATCH] fix: Fix bug preventing removeAll(children) from be called before mount (#3408) Fix bug preventing removeAll(children) from be called before mount. Fixes https://github.com/flame-engine/flame/issues/2933 --- .../lib/src/components/core/component.dart | 6 ++++-- .../flame/test/components/component_test.dart | 20 +++++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/packages/flame/lib/src/components/core/component.dart b/packages/flame/lib/src/components/core/component.dart index f7dfc327185..5f410ac7d46 100644 --- a/packages/flame/lib/src/components/core/component.dart +++ b/packages/flame/lib/src/components/core/component.dart @@ -643,11 +643,13 @@ class Component { /// Removes all the children in the list and calls [onRemove] for all of them /// and their children. - void removeAll(Iterable components) => components.forEach(remove); + void removeAll(Iterable components) { + components.toList(growable: false).forEach(_removeChild); + } /// Removes all the children for which the [test] function returns true. void removeWhere(bool Function(Component component) test) { - removeAll([...children.where(test)]); + children.where(test).toList(growable: false).forEach(_removeChild); } void _removeChild(Component child) { diff --git a/packages/flame/test/components/component_test.dart b/packages/flame/test/components/component_test.dart index bf24deb089a..3cc4f69e4c9 100644 --- a/packages/flame/test/components/component_test.dart +++ b/packages/flame/test/components/component_test.dart @@ -653,6 +653,16 @@ void main() { await game.ready(); expect(child.isMounted, true); }); + + testWithFlameGame( + "can remove component's children before adding the parent", + (game) async { + final c = _ComponentWithChildrenRemoveAll(); + game.add(c); + + await game.ready(); + }, + ); }); group('Removing components', () { @@ -1804,3 +1814,13 @@ FlameTester<_DetachableFlameGame> _myDetachableGame({required bool open}) { }, ); } + +class _ComponentWithChildrenRemoveAll extends Component { + @override + void onMount() { + super.onMount(); + + add(Component()); + removeAll(children); + } +}