Skip to content

Commit

Permalink
feat: Add onComplete callback to AnimationWidget (#2515)
Browse files Browse the repository at this point in the history
Adds optional onComplete callback to SpriteAnimationWidget for asset constructor.
  • Loading branch information
willhlas authored May 1, 2023
1 parent a4f60a8 commit 0b68be8
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
12 changes: 10 additions & 2 deletions packages/flame/lib/src/widgets/animation_widget.dart
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ class SpriteAnimationWidget extends StatelessWidget {
/// A builder function that is called while the loading is on the way
final WidgetBuilder? loadingBuilder;

/// A callback that is called when the animation completes.
final VoidCallback? onComplete;

const SpriteAnimationWidget({
required SpriteAnimation animation,
required SpriteAnimationTicker animationTicker,
Expand All @@ -36,7 +39,8 @@ class SpriteAnimationWidget extends StatelessWidget {
}) : _animationFuture = animation,
_animationTicker = animationTicker,
errorBuilder = null,
loadingBuilder = null;
loadingBuilder = null,
onComplete = null;

/// Loads image from the asset [path] and renders it as a widget.
///
Expand All @@ -52,6 +56,7 @@ class SpriteAnimationWidget extends StatelessWidget {
this.anchor = Anchor.topLeft,
this.errorBuilder,
this.loadingBuilder,
this.onComplete,
super.key,
}) : _animationFuture = SpriteAnimation.load(path, data, images: images),
_animationTicker = null;
Expand All @@ -61,9 +66,12 @@ class SpriteAnimationWidget extends StatelessWidget {
return BaseFutureBuilder<SpriteAnimation>(
future: _animationFuture,
builder: (_, spriteAnimation) {
final ticker = _animationTicker ?? spriteAnimation.ticker();
ticker.completed.then((_) => onComplete?.call());

return InternalSpriteAnimationWidget(
animation: spriteAnimation,
animationTicker: _animationTicker ?? spriteAnimation.ticker(),
animationTicker: ticker,
anchor: anchor,
playing: playing,
);
Expand Down
28 changes: 28 additions & 0 deletions packages/flame/test/widgets/sprite_animation_widget_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -119,5 +119,33 @@ Future<void> main() async {
}
},
);

testWidgets(
'onComplete callback is called when the animation is finished',
(tester) async {
const imagePath = 'test_image_path';
Flame.images.add(imagePath, image);
final spriteAnimationData = SpriteAnimationData.sequenced(
amount: 1,
stepTime: 0.1,
textureSize: Vector2(16, 16),
loop: false,
);

var onCompleteCalled = false;

await tester.pumpWidget(
SpriteAnimationWidget.asset(
path: imagePath,
data: spriteAnimationData,
onComplete: () => onCompleteCalled = true,
),
);

await tester.pumpAndSettle();

expect(onCompleteCalled, isTrue);
},
);
});
}

0 comments on commit 0b68be8

Please sign in to comment.