我们知道AnimationController.forward()可以正向播放动画,AnimationController.reverse()可以反向播放动画,播完即停止。若想让动画播完还可以重新播放不断循环,可以调用
AnimationController.repeat():从头开始循环 AnimationController.repeat(reverse: true):反向循环,从头播到尾,再从尾播到头若要让动画停止,可以调用AnimationController.stop()方法
示例下面的示例中有一个绿色的方形,其宽高从100变大到200,然后再重头开始,不断循环
放款中间有一个停止的原型按钮,按下后可以停止动画
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: AnimationRoute(), ); } } class AnimationRoute extends StatefulWidget { @override AnimationRouteState createState() => AnimationRouteState(); } class AnimationRouteState extends State with SingleTickerProviderStateMixin { Animation animation; AnimationController controller; initState() { super.initState(); // Controller设置动画时长 // vsync设置一个TickerProvider,当前State 混合了SingleTickerProviderStateMixin就是一个TickerProvider controller = AnimationController( duration: Duration(seconds: 5), vsync: this // ); // Tween设置动画的区间值,animate()方法传入一个Animation,AnimationController继承Animation animation = new Tween(begin: 100.0, end: 200.0).animate(controller); controller.repeat(); // controller.repeat(reverse: true); } @override Widget build(BuildContext context) { return AnimatedBuilder( animation: animation, builder: (BuildContext ctx, Widget child) { return Center( child: Container( color: Colors.green, alignment: Alignment.center, width: animation.value, height: animation.value, child: FloatingActionButton( onPressed: (){ controller.stop(); }, child: Text('停止') ), ), ); } ); } @override void dispose() { // 释放资源 controller.dispose(); super.dispose(); } }
若要让动画反向循环播放,只需将controller.repeat()这一行改成controller.repeat(reverse: true)即可
controller.repeat(reverse: true);
作者:野猿新一