如何使用按钮控制动画gif图像?

时间:2018-09-11 08:48:36

标签: dart flutter

我想通过单击按钮来控制gif动画,即,如果我按下“单击我”按钮,则动画开始,然后再次停止动画。我正在参考这个问题How to display an animated picture in Flutter?
我不想将gif图像分成帧,我只需要使用一个gif图像并仅对此进行控制。这是我的代码。

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      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: 3))
      ..stop();
    _animation = new IntTween(begin: 0, end: 7).animate(_controller);
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  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(0, '0');
              return new Image.asset(
                'assets/lips.gif',
                gaplessPlayback: true,
              );
            },
          ),
          new RaisedButton(
            child: new Text('click me'),
            onPressed: () {
              if (_controller.isAnimating) {
                _controller.stop();
              } else {
                _controller.repeat();
              }
            },
          ),
        ],
      ),
    );
  }
}

enter image description here enter image description here

0 个答案:

没有答案