diff --git a/packages/flame/lib/src/components/input/sprite_button_component.dart b/packages/flame/lib/src/components/input/sprite_button_component.dart index bd3d3a4b663..dfbb7076fd8 100644 --- a/packages/flame/lib/src/components/input/sprite_button_component.dart +++ b/packages/flame/lib/src/components/input/sprite_button_component.dart @@ -18,15 +18,9 @@ enum ButtonState { /// through the constructor. class SpriteButtonComponent extends SpriteGroupComponent 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, @@ -35,20 +29,41 @@ class SpriteButtonComponent extends SpriteGroupComponent 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(); } diff --git a/packages/flame/test/components/input/sprite_button_component_test.dart b/packages/flame/test/components/input/sprite_button_component_test.dart index 134279a4a78..b9a6f4f3bc4 100644 --- a/packages/flame/test/components/input/sprite_button_component_test.dart +++ b/packages/flame/test/components/input/sprite_button_component_test.dart @@ -194,6 +194,40 @@ Future 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 {