Search code examples
flutterflame

Flutter : create animation from list of many images


I have 50 images, that each represent the state of an animation, at very short intervals. Like a sprite which shows a little guy swinging an axe.

I need to do a very simple thing : create an animation in flutter that shows this animation.

I found 2 solutions:

But I fear this would be too slow for such short time intervals?

But it feels way over-engineered for my simple use case

What is the correct way to do that in flutter, and have a smooth animation?


Solution

  • You can use Flame's SpriteAnimationWidget for this.

    Since Flutter has tree shaking you don't have to worry about Flame being a large library, everything you don't use will be cleaned away when you build your app.

    To use the SpriteAnimationWidget simple do this:

    SpriteAnimationWidget.asset(
      path: 'your_spritesheet.png',
      data: SpriteAnimationData.sequenced(
        amount: 50,
        stepTime: 0.1,
        textureSize: Vector2(32, 32),
      ),
    );
    

    This is if your 50 images are in a spritesheet, if they are not, you can do this:

    final sprites = images.map((image) => Sprite(image)).toList();
    SpriteAnimationWidget(
      animation: SpriteAnimation.spriteList(
        sprites,
        stepTime: 0.1,
      ),
    );
    

    where images would be a list of your Image objects.

    0.1 in both the examples is the time between frames, so with 0.1 it would animate with 10 frames per second.

    Here you can see and examples of it running:

    https://examples.flame-engine.org/#/Widgets_Sprite%20Animation%20Widget