How to display an animated picture in Flutter?

2019-03-28 20:18发布

问题:

I want to display an animated picture, whatever its format, in Flutter. The fact is that currently there seems to be only one solution available, video_loader. This works only on full screen, but it doesn't fit my use case.

Any idea on how I could sort this out?

回答1:

Now, Image widget Supports GIF. (April 18)

For Ex.

new Image(image: new AssetImage("assets/ajax-loader.gif"))



回答2:

You can split the frames into separate images using https://ezgif.com/split and add them as assets in your pubspec.yaml.

Then use an Animation<int> to select the correct frame to display. Make sure to set gaplessPlayback: true to avoid flickering.

For example, the following code displays the frames of an animated GIF that was created by Guillaume Kurkdjian.

import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      theme: new ThemeData.dark(),
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  State createState() => new MyHomePageState();
}

class MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
  AnimationController _controller;
  Animation<int> _animation;

  @override
  void initState() {
    _controller = new AnimationController(vsync: this, duration: const Duration(seconds: 5))
      ..repeat();
    _animation = new IntTween(begin: 0, end: 116).animate(_controller);
  }

  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          new AnimatedBuilder(
            animation: _animation,
            builder: (BuildContext context, Widget child) {
              String frame = _animation.value.toString().padLeft(3, '0');
              return new Image.asset(
                'assets/frame_${frame}_delay-0.04s.png',
                gaplessPlayback: true,
              );
            },
          ),
          new Text('Image: Guillaume Kurkdjian', style: new TextStyle(fontStyle: FontStyle.italic)),
        ],
      ),
    );
  }
}


标签: dart flutter