增加动画状态控制, 比如正向播放结束时候status为AnimationStatus.completed,反向播放结束时候状态为AnimationStatus.dismissed。 如果继续播放可以使用 forward() 或者 reverse() 从新开始。
状态的监听可以在AnimationController或者Animation中添加addStatusListener()处理即可。
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main(List<String> args) {
runApp(const LogoApp());
}
class AnimatedLogo extends AnimatedWidget {
const AnimatedLogo({super.key, required super.listenable});
@override
Widget build(BuildContext context) {
final animation = listenable as Animation<double>;
return Center(
child: Container(
margin: const EdgeInsets.symmetric(vertical: 10),
height: animation.value,
width: animation.value,
child: const FlutterLogo(),
),
);
}
}
class LogoApp extends StatefulWidget {
const LogoApp({super.key});
@override
State<LogoApp> createState() => _LogoAppState();
}
class _LogoAppState extends State<LogoApp> with SingleTickerProviderStateMixin {
late AnimationController controller;
late Animation animation;
@override
void initState() {
super.initState();
controller = AnimationController(
vsync: this,
duration: const Duration(seconds: 3),
)..addStatusListener((status) {
print("inside controller.");
if (status == AnimationStatus.completed) {
controller.reverse();
} else if (status == AnimationStatus.dismissed) {
controller.forward();
}
});
animation = Tween<double>(begin: 0, end: 300).animate(controller)
..addStatusListener(
(status) {
if (kDebugMode) {
print('$status');
}
// 此处也可
// if (status == AnimationStatus.completed) {
// controller.reverse();
// } else if (status == AnimationStatus.dismissed) {
// controller.forward();
// }
},
);
controller.forward();
}
@override
Widget build(BuildContext context) => AnimatedLogo(listenable: animation);
}