效果以下圖:
代碼
import 'package:flutter/material.dart';
import 'package:sprintf/sprintf.dart'; //這個是一個拼接字符串的flutter庫,主要是爲了使用方便,你能夠選擇不使用,這樣的話你須要本身拼接圖片路徑
class ImagesAnimation extends StatefulWidget {
final double w;
final double h;
final ImagesAnimationEntry entry;
final int durationSeconds;
ImagesAnimation({Key key, this.w : 80, this.h : 80, this.entry, this.durationSeconds : 3}):super(key:key);
@override
_InState createState() {
return _InState();
}
}
class _InState extends State<ImagesAnimation> with TickerProviderStateMixin{
AnimationController _controller;
Animation<int> _animation;
@override
void initState() {
super.initState();
_controller = new AnimationController(vsync: this, duration: Duration(seconds: widget.durationSeconds))
..repeat();
_animation = new IntTween(begin: widget.entry.lowIndex, end: widget.entry.highIndex).animate(_controller);
//widget.entry.lowIndex 表示從第幾下標開始,如0;widget.entry.highIndex表示最大下標:如7
}
@override
Widget build(BuildContext context) {
return new AnimatedBuilder(
animation: _animation,
builder: (BuildContext context, Widget child) {
String frame = _animation.value.toString();
return new Image.asset(
sprintf(widget.entry.basePath, [frame]), //根據傳進來的參數拼接路徑
gaplessPlayback: true, //避免圖片閃爍
width: widget.w,
height: widget.h,
);
},
);
}
}
class ImagesAnimationEntry {
int lowIndex = 0;
int highIndex = 0;
String basePath;
ImagesAnimationEntry(this.lowIndex, this.highIndex, this.basePath);
}
使用的地方:
ImagesAnimation(w: 100, h: 100, entry: ImagesAnimationEntry(1, 7, "images/men_sport_%s.png")),
//"images/men_sport_%s.png" 表示圖片在你本地的路徑,%s會被下標代替