Flutter 汇总请看这里
可以控制什么时候播放,重新播放,暂停续播的帧动画widget
- 如需完整代码请点击---->git地址
在 pubspec.yaml中添加依赖:
frame_animate_widget: ^1.0.0
渲染widget后直接播放
//list 图片帧集合,
//interval 切帧时间,
FrameAnimationImage(list, width: 220, height: 200, interval: 50)
渲染widget后手动控制播放
//由GlobalKey跨widget改变状态
final GlobalKey<FrameAnimationImageState> _key = new GlobalKey<FrameAnimationImageState>();
//start: false 此时要告诉widget 开始不播放动画
FrameAnimationImage(_key, list,
width: 220, height: 200, interval: 50, start: false)
//控制 widget 开始/继续;结束;重新开始 播放帧
_key.currentState.startAnimation();
_key.currentState.stopAnimation();
_key.currentState.reStartAnimation();
源码
import 'package:flutter/material.dart';
class FrameAnimationImage extends StatefulWidget {
final List<String> _assetList;
final double width;
final double height;
bool start = true;
int interval = 200;
FrameAnimationImage(Key key, this._assetList,
{this.width, this.height, this.interval, this.start})
: super(key: key);
@override
State<StatefulWidget> createState() {
return FrameAnimationImageState();
}
}
class FrameAnimationImageState extends State<FrameAnimationImage>
with SingleTickerProviderStateMixin {
// 动画控制
Animation<double> _animation;
AnimationController _controller;
int interval = 200;
@override
void initState() {
super.initState();
if (widget.interval != null) {
interval = widget.interval;
}
final int imageCount = widget._assetList.length;
final int maxTime = interval * imageCount;
// 启动动画controller
_controller = new AnimationController(
duration: Duration(milliseconds: maxTime), vsync: this);
_controller.addStatusListener((AnimationStatus status) {
if (status == AnimationStatus.completed) {
_controller.forward(from: 0.0); // 完成后重新开始
}
});
_animation = new Tween<double>(begin: 0, end: imageCount.toDouble())
.animate(_controller)
..addListener(() {
setState(() {
// the state that has changed here is the animation object’s value
});
});
if (widget.start) {
_controller.forward();
}
}
void startAnimation() => _controller.forward();
void stopAnimation() => _controller.stop();
void reStartAnimation(){
_controller.reset();
_controller.forward();
}
@override
void didUpdateWidget(FrameAnimationImage oldWidget) {
// TODO: implement didUpdateWidget
super.didUpdateWidget(oldWidget);
print("didUpdateWidget called");
if (widget.start) {
_controller.forward();
}
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
int ix = _animation.value.floor() % widget._assetList.length;
List<Widget> images = [];
// 把所有图片都加载进内容,否则每一帧加载时会卡顿
for (int i = 0; i < widget._assetList.length; ++i) {
if (i != ix) {
images.add(Image.asset(
widget._assetList[i],
width: 0,
height: 0,
));
}
}
images.add(Image.asset(
widget._assetList[ix],
width: widget.width,
height: widget.height,
));
return Stack(alignment: AlignmentDirectional.center, children: images);
}
}