在使用AnimationController的animateTo方法时,需要注意animateTo第一个参数需要设置最终值,而第二个参数duration设置动画时间。如果动画时间设置过短或者过长,则会导致动画在结束时自动回到起始位置。为了避免这种情况的发生,需要根据动画的实际需求来设置合适的动画时间,避免时间过短或过长的情况。
示例代码:
class MyWidget extends StatefulWidget {
@override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State
with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation _animation;
@override
void initState() {
super.initState();
_controller = AnimationController(
duration: const Duration(milliseconds: 500),
vsync: this,
);
_animation = CurvedAnimation(
parent: _controller,
curve: Curves.easeInOutCirc,
);
_animation.addStatusListener((status) {
if (status == AnimationStatus.completed) {
_controller.reverse();
} else if (status == AnimationStatus.dismissed) {
_controller.forward();
}
});
_controller.forward();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
width: _animation.value * 200,
height: _animation.value * 200,
color: Colors.blueAccent,
),
),
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
}