Skip to content

Commit

Permalink
fix: Fix bug preventing removeAll(children) from be called before mou…
Browse files Browse the repository at this point in the history
…nt (#3408)

Fix bug preventing removeAll(children) from be called before mount.

Fixes #2933
  • Loading branch information
luanpotter authored Dec 14, 2024
1 parent ce7822a commit 726cb8b
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
6 changes: 4 additions & 2 deletions packages/flame/lib/src/components/core/component.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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<Component> components) => components.forEach(remove);
void removeAll(Iterable<Component> 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) {
Expand Down
20 changes: 20 additions & 0 deletions packages/flame/test/components/component_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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', () {
Expand Down Expand Up @@ -1804,3 +1814,13 @@ FlameTester<_DetachableFlameGame> _myDetachableGame({required bool open}) {
},
);
}

class _ComponentWithChildrenRemoveAll extends Component {
@override
void onMount() {
super.onMount();

add(Component());
removeAll(children);
}
}

0 comments on commit 726cb8b

Please sign in to comment.