AnimationController

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

核心代码:

class RowState extends State<Row> with TickerProviderStateMixin{
  double paddingLeft = 150;
  AnimationController animationController;
  int n = 0;

  @override
  void initState() {
    animationController = AnimationController(
      vsync: this,
      duration: Duration(seconds: 4),
      lowerBound: 10,
      upperBound: 150,
    );
    animationController.addListener(() {
      n++;
      setState(() {});
    });
    animationController.animateTo(paddingLeft);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 60,
      width: double.infinity,
      alignment: Alignment.centerLeft,
      padding: EdgeInsets.only(
        left: animationController.value,
      ),
      child: Text('$n  ${animationController.value}'),
    );
  }
}

总结:

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

2、动画实现原理:AnimationController监听器中进行更新控件,执行AnimationController.animateTo()会持续触发监听器,直到达到移动值后停止触发。

3、注意在2中,如果AnimationController的移动值要在lowerBound和upperBound之间(当达到移动值后会停止触发监听器),否则当AnimationController.value达到最大值或最小值后虽然该值不会再改变了,但仍会触发监听器刷新控件。(如paddingLeft值为200,会发现animationController.value直到150数值不再增加,而n还在增加一段时间才会停止)。为了避免这种无效刷新,设置lowerBound和upperBound要包含将要移动值。

猜你喜欢

转载自blog.csdn.net/yufumatou/article/details/109120600