Skip to content

Commit

Permalink
fix: Add assertion when trying to set "current" that doesn't exist (#…
Browse files Browse the repository at this point in the history
…3258)

Currently when setting `current` in `SpriteAnimationGroupComponent` and
`SpriteGroupComponent` we silently fail if the key isn't in the map.
This PR adds assertions so that we at least warn about it in debug mode.
  • Loading branch information
spydon authored Aug 9, 2024
1 parent 9ff6dfe commit 267d680
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,12 @@ class SpriteAnimationGroupComponent<T> extends PositionComponent
///
/// Will update [size] if [autoResize] is true.
set current(T? value) {
assert(_animations != null, 'Animations not set');
assert(
_animations!.keys.contains(value),
'Animation not found for key: $value',
);

final changed = value != current;
_current = value;
_resizeToSprite();
Expand Down
3 changes: 3 additions & 0 deletions packages/flame/lib/src/components/sprite_group_component.dart
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@ class SpriteGroupComponent<T> extends PositionComponent
///
/// Will update [size] if [autoResize] is true.
set current(T? value) {
assert(_sprites != null, 'Sprites not set');
assert(_sprites!.keys.contains(value), 'Sprite not found for key: $value');

final changed = _current != value;
_current = value;
_resizeToSprite();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,16 @@ Future<void> main() async {
component.current = _AnimationState.running;
expect(component.animation, animation2);
});

test('Asserts that map contains key', () {
expect(
() {
SpriteAnimationGroupComponent<String>(animations: {}).current =
'non-existent-key';
},
failsAssert('Animation not found for key: non-existent-key'),
);
});
});

group('SpriteAnimationGroupComponent.shouldRemove', () {
Expand Down
10 changes: 10 additions & 0 deletions packages/flame/test/components/sprite_group_component_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,16 @@ Future<void> main() async {
component.current = _SpriteState.running;
expect(component.sprite, sprite2);
});

test('Asserts that map contains key', () {
expect(
() {
SpriteGroupComponent<String>(sprites: {}).current =
'non-existent-key';
},
failsAssert('Sprite not found for key: non-existent-key'),
);
});
});

group('SpriteComponent.autoResize', () {
Expand Down

0 comments on commit 267d680

Please sign in to comment.