どうも、ちょげ(@chogetarou)です。
CurveAnimationをAnimationControllerで使うには、どうしたらいいのでしょうか?
方法

CurveAnimationをAnimationControllerで使うには、まず変数を用意します。
late Animation _curveAnimation;
そして、initStateで、変数を次のように初期化します。
_curveAnimation = Tween(begin: 0.5, end: 1.0)
.animate(CurvedAnimation(parent: _controller, curve: Curves.bounceIn));
ポイントは、直接ではなく、Tweenを経由していることです。
Tweenによって、Curveアニメーションの値の振り幅を決めることが出来ます。
そして、Tweenのanimateメソッドで、CurveAnimationクラスを指定します。
これで、CurveAnimationをコントローラで使えるようになります。
Transform.scale(
scale: _curveAnimation.value, //カーブアニメーションの設定
child: Container(
width: 150,
height: 150,
color: Colors.green,
),
),
全体のコード
class Sample extends StatefulWidget {
@override
_SampleState createState() => _SampleState();
}
class _SampleState extends State<Sample> with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation _curveAnimation;
var isChanged = false;
@override
void initState() {
super.initState();
_controller =
AnimationController(duration: Duration(seconds: 2), vsync: this);
_controller.addStatusListener((status) {
if (status == AnimationStatus.completed) {
setState(() {
isChanged = true;
});
} else {
setState(() {
isChanged = false;
});
}
});
_curveAnimation = Tween(begin: 0.5, end: 1.0)
.animate(CurvedAnimation(parent: _controller, curve: Curves.bounceIn));
}
@override
void dispose() {
super.dispose();
_controller.dispose();
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
AnimatedBuilder(
animation: _controller,
builder: (BuildContext context, Widget? child) {
return Transform.scale(
scale: _curveAnimation.value,
child: child
);
},
child: Container(
width: 150,
height: 150,
color: Colors.green,
),
),
TextButton(
onPressed: () {
isChanged ? _controller.reverse() : _controller.forward();
},
child: Text('Animate!')
)
],
);
}
}
コメント