import 'package:flutter/material.dart';
class FrameAnimCtrl extends StatefulWidget {
? ///每一幀的間隔 毫秒
? final int interval;
? //循環(huán)播放
? final bool loop;
? //沒有辦法自己銷毀自己, 這里選擇回調(diào)函數(shù)給父節(jié)點(diǎn)
? //只播放一次時, 完成回調(diào)
? 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;
? //當(dāng)前初始化是正序
? 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;
? }
}