我有一个简单的动画:
Animation<double> animation;
Tween<double> tween = Tween(begin: 1, end: 1.15);
AnimationController animationController;
@override
void initState() {
super.initState();
animationController =
AnimationController(vsync: this, duration: Duration(milliseconds: 300));
animation = animationController.drive(tween);
}
Run Code Online (Sandbox Code Playgroud)
我想要的是 ?
使这个动画重复例如 20 次。
我在发布这个问题之前尝试过什么?
1- 此方法没有使我重复此动画的参数或方式,例如 20 次。
它重复,重复,永远重复:
animationController.repeat();
Run Code Online (Sandbox Code Playgroud)
2- 使用简单的循环。它挂起我的应用程序,它需要停止整个应用程序并重新运行它以解决挂起的. 循环似乎完全不处理期货:
do {
animationController.forward().then((x) {
animationController.reverse().then((x) {
repeats++;
});
});
} while (repeats < 20);
Run Code Online (Sandbox Code Playgroud)
3- 制作 int 变量并添加一个监听器 .. 等,它正在工作,但似乎这不是最好的方法:
int repeats = 0;
animation.addStatusListener((status) {
if (repeats < 20) {
if (status == AnimationStatus.completed) {
animationController.reverse();
} else if (status == AnimationStatus.dismissed) {
animationController.forward();
}
repeats++;
} });
Run Code Online (Sandbox Code Playgroud)
4- make 链 then 。**对此不予评论**:
animationController.forward().then((x) {
animationController.reverse().then((x) {
animationController.forward().then((x) {
animationController.reverse().then((x) {
animationController.forward().then((x) {
animationController.reverse();
});
});
});
});
});
Run Code Online (Sandbox Code Playgroud)
现在,我怎么能重复动画 20 次呢?
你可以试试看:
5 - 使用 TickerFuture 从重复中返回,设置超时然后停止动画。
AnimationController _animationController;
@override
void initState() {
super.initState();
_animationController = AnimationController(
vsync: this,
duration: Duration(seconds: 3),
);
_animationController.addListener(() => setState(() {}));
TickerFuture tickerFuture = _animationController.repeat();
tickerFuture.timeout(Duration(seconds: 3 * 10), onTimeout: () {
_animationController.forward(from: 0);
_animationController.stop(canceled: true);
});
}
Run Code Online (Sandbox Code Playgroud)
这可以在没有计时器的情况下通过扩展方法轻松完成:
extension on AnimationController {
void repeatEx({@required int times}) {
var count = 0;
addStatusListener((status) {
if (status == AnimationStatus.completed) {
if (++count < times) {
reverse();
}
} else if (status == AnimationStatus.dismissed) {
forward();
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
你可以这样使用它:
_controller = AnimationController(
vsync: this,
duration: const Duration(seconds: 1),
)
..repeatEx(times: 10)
..forward();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2995 次 |
| 最近记录: |