且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Flutter中将Curves类动画添加到AnimationController?

更新时间:2023-12-02 23:27:58

您将要同时使用动画控制器和补间,这将允许您添加 Curves.bounceOut

You'll want to use both an animation controller and a tween, which will allow you to add Curves.bounceOut.

在代码中的某些位置添加:

Somewhere in your code add:

AnimationController _controller;
var scaleAnimation;

在您的 initState()方法中:

_controller = new AnimationController(
 duration: new Duration(milliseconds: 300),
 vsync: this
)
..addListener(() {
  setState(() {});
});
scaleAnimation = new Tween(
  begin: 0.5,
  end: 1.0,
).animate(new CurvedAnimation(
  parent: _controller,
  curve: Curves.bounceOut
));

请注意 .. addListener()是不错的dart代码,可让您轻松添加侦听器。补间基本上是告诉您的动画,它需要从开始中的值到 end 中的值 AnimationController 中给出的时间范围。要在代码中使用此值,您现在可以设置动画结果的比例:

Note the ..addListener() is a nice bit of dart code that allows you to add a listener easily. The Tween is basically telling your animation that it needs to go from the value in begin to the value in end within the timeframe given in the AnimationController. To use this value in your code you can now just set the scale of your result of your animation:

child: Transform.scale(
  scale: scaleAnimation.value,
  child: Container(
    width: 150.0,
    height: 150.0,
    color: Colors.green,
  ),
),

以及调用动画时

编辑:

将窗口小部件更改为此:

Change your widget to this:

child: isChanging ? Transform.scale(
  scale: scaleAnimation.value,
  child: Container(
    width: 150.0,
    height: 150.0,
    color: Colors.green,
  ),
) : Transform.scale(
  scale: 1.0,
  child: Container(
    width: 150.0,
    height: 150.0,
    color: Colors.green,
  ),
),

保持开始 end 参数为 0.5 1.0 ,但是在转发控制器之前,在您的 onTap()方法中添加:

Keep your begin and end parameters as 0.5 and 1.0 respectively, but in your onTap() method before you forward your controller add:

onTap: () {
  setState(() {
    isChanging = true
  });
  _controller.forward(from: 0.0);
}

在代码中的任何位置添加 bool isChanging行。最后,您需要在动画结束时重置显示的小部件,因此将scaleAnimation更改为:

And anywhere in your code add the line bool isChanging. Finally you'll want to reset the shown widget at the end of your animation, so change your scaleAnimation to:

child: Transform.scale(
  scale: scaleAnimation.value,
  child: Container(
    width: 150.0,
    height: 150.0,
    color: Colors.green,
  ),
)..addStatusListener((AnimationStatus status) {
  if (status == AnimationStatus.completed) { //the animation is finished
    _controller.reset();
    setState(() {
      isChanging = false;
    }
  }
});