diff --git a/packages/flame/lib/src/components/core/component.dart b/packages/flame/lib/src/components/core/component.dart index b78b93670f..022ecd1f30 100644 --- a/packages/flame/lib/src/components/core/component.dart +++ b/packages/flame/lib/src/components/core/component.dart @@ -662,11 +662,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 bf24deb089..3cc4f69e4c 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); + } +}