当前位置: 代码迷 >> 综合 >> AnimationController
  详细解决方案

AnimationController

热度:38   发布时间:2024-02-29 09:52:56.0

需求:通过AnimationController实现控件平移动画效果。

核心代码:

class RowState extends State<Row> with TickerProviderStateMixin{double paddingLeft = 150;AnimationController animationController;@overridevoid initState() {animationController = AnimationController(vsync: this,duration: Duration(seconds: 2),lowerBound: 10,upperBound: 150,);animationController.addListener(() {setState(() {});});super.initState();}@overridevoid didUpdateWidget(Row oldWidget) {animationController.animateTo(paddingLeft);super.didUpdateWidget(oldWidget);}@overrideWidget build(BuildContext context) {return Container(height: 60,width: double.infinity,alignment: Alignment.centerLeft,padding: EdgeInsets.only(left: animationController.value,),child: Text('${animationController.value}'),);}
}

总结:

1、AnimationController.value起始值为最小值

2、动画实现原理:控件执行build方法会触发didUpdateWidget生命周期,在该方法里执行AnimationController.animateTo()进行动画值更新,从而触发监听器,再在监听器里更新控件触发build方法,如此循环实现动画(build -》didUpdateWidget -》AnimationController.animateTo() -》setState() -》build)

3、注意在2中,如果AnimationController的移动值要在lowerBound和upperBound之间(当达到移动值后会停止触发监听器),否则当AnimationController.value达到最大值或最小值后虽然该值不会再改变了,但继续调用.animateTo(200),仍会触发监听器从而刷新控件而由于无法达到移动值进入死循环状态。为了避免这种无效刷新,设置lowerBound和upperBound要包含将要移动值。

  相关解决方案