Skip to content

Commit

Permalink
feat: Allow changing parent from null parent (flame-engine#1662)
Browse files Browse the repository at this point in the history
changeParent should be allowed even when the current parent is null.
  • Loading branch information
spydon authored and st-pasha committed May 29, 2022
1 parent b52d115 commit 2750553
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/component.dart
Original file line number Diff line number Diff line change
Expand Up @@ -233,8 +233,10 @@ class Component {
set parent(Component? newParent) {
if (newParent == null) {
removeFromParent();
} else if (_parent == null) {
addToParent(newParent);
} else {
changeParent(newParent);
newParent.lifecycle._adoption.add(this);
}
}

Expand Down Expand Up @@ -603,7 +605,7 @@ class Component {
/// Changes the current parent for another parent and prepares the tree under
/// the new root.
void changeParent(Component newParent) {
newParent.lifecycle._adoption.add(this);
parent = newParent;
}

//#endregion
Expand Down
20 changes: 20 additions & 0 deletions packages/flame/test/components/component_lifecycle_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,26 @@ void main() {
},
);

testWithFlameGame(
'component mounted completes when changing parent from a null parent',
(game) async {
final parent = LifecycleComponent('parent');
final child = LifecycleComponent('child');
game.add(parent);

final mounted = child.mounted;
await game.ready();

child.changeParent(parent);
game.update(0);
await game.ready();

expect(child.parent, parent);
expect(child.isMounted, true);
await expectLater(mounted, completes);
},
);

testWithFlameGame(
'Component.mounted completes after the component is mounted',
(game) async {
Expand Down

0 comments on commit 2750553

Please sign in to comment.