Skip to content

Commit

Permalink
fix: Properly update sprites in SpriteButtonComponent (#3013)
Browse files Browse the repository at this point in the history
Previously if you replaced a sprite in a `SpriteButtonComponent` with
`component.button = ...` it didn't update the button visually since the
`sprites` map wasn't updated, this PR solves that.
  • Loading branch information
spydon authored Feb 1, 2024
1 parent 4e6968a commit 23cf8b9
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,9 @@ enum ButtonState {
/// through the constructor.
class SpriteButtonComponent extends SpriteGroupComponent<ButtonState>
with TapCallbacks {
/// Callback for what should happen when the button is pressed.
void Function()? onPressed;

Sprite? button;
Sprite? buttonDown;

SpriteButtonComponent({
this.button,
this.buttonDown,
Sprite? button,
Sprite? buttonDown,
this.onPressed,
super.position,
Vector2? size,
Expand All @@ -35,20 +29,41 @@ class SpriteButtonComponent extends SpriteGroupComponent<ButtonState>
super.anchor,
super.children,
super.priority,
}) : super(
}) : _button = button,
_buttonDown = buttonDown,
super(
current: ButtonState.up,
size: size ?? button?.originalSize,
);

/// Callback for what should happen when the button is pressed.
void Function()? onPressed;

Sprite? _button;
Sprite? _buttonDown;

Sprite get button => _button!;
Sprite get buttonDown => _buttonDown ?? button;

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

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

@override
void onMount() {
assert(
button != null,
_button != null,
'The button sprite has to be set either in onLoad or in the constructor',
);
sprites = {
ButtonState.up: button!,
ButtonState.down: buttonDown ?? button!,
ButtonState.up: button,
ButtonState.down: buttonDown,
};
super.onMount();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,40 @@ Future<void> main() async {
},
);
});

testWithFlameGame('can change button sprites', (game) async {
final buttonSheet = SpriteSheet.fromColumnsAndRows(
image: image,
columns: 1,
rows: 2,
);

final button = SpriteButtonComponent(
button: buttonSheet.getSpriteById(0),
buttonDown: buttonSheet.getSpriteById(1),
);

await game.ensureAdd(button);

expect(
button.sprites,
{
ButtonState.up: buttonSheet.getSpriteById(0),
ButtonState.down: buttonSheet.getSpriteById(1),
},
);

button.button = buttonSheet.getSpriteById(1);
button.buttonDown = buttonSheet.getSpriteById(0);

expect(
button.sprites,
{
ButtonState.up: buttonSheet.getSpriteById(1),
ButtonState.down: buttonSheet.getSpriteById(0),
},
);
});
}

class SimpleStatelessWidget extends StatelessWidget {
Expand Down

0 comments on commit 23cf8b9

Please sign in to comment.