Skip to content

Commit

Permalink
fix: Take unmounted adds into consideration (#2770)
Browse files Browse the repository at this point in the history
The previous fix accidentally didn't take into consideration if the parent was unmounted.
  • Loading branch information
spydon committed Sep 24, 2023
1 parent 89e8427 commit be28a44
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 9 deletions.
17 changes: 9 additions & 8 deletions packages/flame/lib/src/components/core/component.dart
Expand Up @@ -585,19 +585,20 @@ class Component {
}

FutureOr<void> _addChild(Component child) {
final game = findGame();
if (child._parent != null) {
final game = findGame() ?? child.findGame();
if ((!isMounted && !child.isMounted) || game == null) {
child._parent?.children.remove(child);
child._parent = this;
children.add(child);
} else if (child._parent != null) {
if (child.isRemoving) {
// If the child is going to be added to the same parent as it previously
// had we need to remove it from the previous remove event from the
// queue.
game!.dequeueRemove(child);
game.dequeueRemove(child);
_clearRemovingBit();
}
game!.enqueueMove(child, this);
game.enqueueMove(child, this);
} else if (isMounted && !child.isMounted) {
child._parent = this;
game!.enqueueAdd(child, this);
game.enqueueAdd(child, this);
} else {
child._parent = this;
// This will be reconciled during the mounting stage
Expand Down
2 changes: 1 addition & 1 deletion packages/flame/test/collisions/collision_type_test.dart
Expand Up @@ -188,7 +188,7 @@ void main() {
final actives = generateBlocks(CollisionType.active);
final passives = generateBlocks(CollisionType.passive);
final inactives = generateBlocks(CollisionType.inactive);
await game.ensureAddAll((actives + passives + inactives)..shuffle());
await game.ensureAddAll((actives + passives + inactives)..shuffle(rng));
game.update(0);
expect(
actives.every((c) => c.collidedWithExactly(actives + passives)),
Expand Down
18 changes: 18 additions & 0 deletions packages/flame/test/components/component_test.dart
Expand Up @@ -451,6 +451,24 @@ void main() {
},
);

testWithFlameGame(
'move a component from a mounted parent to an unmounted one',
(game) async {
final child = Component();
final mountedParent = Component(children: [child]);
final unmountedParent = Component();
await game.ensureAdd(mountedParent);
unmountedParent.add(child);
game.update(0);
expect(child.parent, unmountedParent);
expect(mountedParent.children, []);
expect(unmountedParent.children, [child]);
expect(child.isMounted, isFalse);
await game.ensureAdd(unmountedParent);
expect(child.isMounted, isTrue);
},
);

testWithFlameGame(
'swapping between multiple parents in the same tick',
(game) async {
Expand Down

0 comments on commit be28a44

Please sign in to comment.