Skip to content

Commit

Permalink
fix: Disallow mutatation of SpriteGroupComponent.sprites (#3185)
Browse files Browse the repository at this point in the history
Many users try to modify the `SpriteGroupComponent.sprites` map, but
that doesn't work since it has to go through the setter, so this PR
makes the returned map from the getter unmodifiable.
You can either set it by using the setter or set a particular sprite by
using the newly created `updateSprite` method.
  • Loading branch information
spydon authored Jun 5, 2024
1 parent 5277340 commit 7c40034
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,12 @@ class SpriteButtonComponent extends SpriteGroupComponent<ButtonState>

set button(Sprite value) {
_button = value;
sprites?[ButtonState.up] = value;
updateSprite(ButtonState.up, value);
}

set buttonDown(Sprite value) {
_buttonDown = value;
sprites?[ButtonState.down] = value;
updateSprite(ButtonState.down, value);
}

@override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ class SpriteAnimationGroupComponent<T> extends PositionComponent
/// Returns the map of animation state and their corresponding animations.
///
/// If you want to change the contents of the map use the animations setter
/// and pass in a new map of animations
/// and pass in a new map of animations.
Map<T, SpriteAnimation>? get animations =>
_animations != null ? Map.unmodifiable(_animations!) : null;

Expand Down
13 changes: 12 additions & 1 deletion packages/flame/lib/src/components/sprite_group_component.dart
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,12 @@ class SpriteGroupComponent<T> extends PositionComponent
bool get autoResize => _autoResize;

/// Returns the sprites map.
Map<T, Sprite>? get sprites => _sprites;
///
/// If you want to change the contents of the map use the sprites setter
/// and pass in a new map of sprites, or use [updateSprite] to update a
/// specific sprite.
Map<T, Sprite>? get sprites =>
_sprites != null ? Map.unmodifiable(_sprites!) : null;

/// Sets the given [value] as sprites map.
set sprites(Map<T, Sprite>? value) {
Expand All @@ -90,6 +95,12 @@ class SpriteGroupComponent<T> extends PositionComponent
}
}

/// Updates the sprite for the given key.
void updateSprite(T key, Sprite sprite) {
_sprites![key] = sprite;
_resizeToSprite();
}

/// Sets the given value of autoResize flag.
///
/// Will update the [size] to fit srcSize of
Expand Down

0 comments on commit 7c40034

Please sign in to comment.