import 'package:flutter/material.dart';
class FrameAnimCtrl extends StatefulWidget {
///每一帧的间隔 毫秒
final int interval;
//循环播放
final bool loop;
//没有办法自己销毁自己, 这里选择回调函数给父节点
//只播放一次时, 完成回调
final Function onend;
//图片集合
final List<String> imageCaches;
final double width;
final double height;
final Color backColor;
//逆序播放(先正 后反)
final bool reverse;
FrameAnimCtrl(
{Key key,
this.interval = 100,
this.loop = true,
this.imageCaches,
this.width,
this.height,
this.backColor,
this.onend,
this.reverse = false})
: assert(imageCaches != null),
super(key: key);
@override
_FrameAnimCtrlState createState() => _FrameAnimCtrlState();
}
class _FrameAnimCtrlState extends State<FrameAnimCtrl> {
bool _disposed;
Duration _duration;
int _imageIndex;
Container _container;
bool isPlay;
//当前初始化是正序
bool curfx = true;
@override
void initState() {
super.initState();
_disposed = false;
_duration = Duration(milliseconds: widget.interval);
_imageIndex = 0;
_container = Container(height: widget.height, width: widget.width);
isPlay = true;
_updateImage();
}
void _updateImage() {
if (_disposed || widget.imageCaches.isEmpty) {
return;
}
setState(() {
if (_imageIndex >= widget.imageCaches.length - 1) {
if (widget.reverse == false) {
curfx = true;
_imageIndex = 0;
if (widget.loop == false) {
isPlay = false;
if (widget.onend != null) {
widget.onend();
}
return;
}
} else {
curfx = false;
}
}
//逆序播放回来了
else if (_imageIndex == 0 && curfx == false) {
curfx = true;
if (widget.loop == false) {
isPlay = false;
if (widget.onend != null) {
widget.onend();
}
return;
}
}
_container = Container(
color: widget.backColor,
child: Image.asset(widget.imageCaches[_imageIndex]),
height: widget.height,
width: widget.width);
if (curfx == true) {
_imageIndex++;
} else {
_imageIndex--;
}
});
if (isPlay == false) {
return;
}
Future.delayed(_duration, () {
_updateImage();
});
}
@override
void dispose() {
super.dispose();
_disposed = true;
widget.imageCaches.clear();
}
@override
Widget build(BuildContext context) {
return _container;
}
}