配置vsync,需要实现一下with SingleTickerProviderStateMixin
class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin{// 定义 AnimationControllerlate AnimationController _controller;@overridevoid initState() {super.initState();// 初始化 AnimationController_controller = AnimationController(duration: const Duration(milliseconds: 500),vsync:this, // 让程序和手机的刷新频率统一);}@overrideWidget build(BuildContext context) {return Scaffold(appBar: AppBar(title: const Text('标题'),),body: Center(child: Column(children: [SlideTransition(// 方块的宽度100,设置x轴y轴位移 0.5:也就是x轴向右移动50,同时向下移动50position: _controller.drive(Tween(begin: Offset(0, 0),end: Offset(0.5, 0.5))),child: Container(alignment: Alignment.center,width: 100,height: 100,color: Colors.red,),),ElevatedButton(onPressed: (){_controller.repeat(reverse: true); // repeat(reverse: true) 是否循环播放}, child: const Text('重复')),ElevatedButton(onPressed: (){_controller.stop();}, child: const Text('停止')),ElevatedButton(onPressed: (){_controller.forward();}, child: const Text('移动')),ElevatedButton(onPressed: (){_controller.reverse();}, child: const Text('返回')),ElevatedButton(onPressed: (){_controller.reset();}, child: const Text('重置')),],),),);}
}
第二种写法
初始化时,动画时长设置为10秒
duration: const Duration(milliseconds: 10000),position:Tween(begin: Offset(0, 0), end: Offset(0.5, 0.5)).chain(CurveTween(curve: Curves.bounceInOut)) // 配置动画效果.chain(CurveTween(curve: Interval(0.3, 0.6))) // 当前时间点30%开始(也就是第三秒开始移动)运动到60%结束(第6秒结束).animate(_controller),