[Flutter]AnimationControllerでCurveを使う方法

Flutter

どうも、ちょげ(@chogetarou)です。

AnimationControllerでCurveを使うには、どうしたらいいのでしょうか?

スポンサーリンク

方法

インターフェース, インターネット, プログラム, ブラウザ, Www

AnimationControllerでCurveを使うには、CurvedAnimationクラスを使います。

CurvedAnimationクラスの引数「parent」に、「AnimationController」を指定することで、カーブアニメーションが使えるようになります。

    _controller = AnimationController(
      duration: Duration(seconds: 1),
      vsync: this,
    );

    _controller.addListener(() {
      setState(() {});
      print(_controller.value);
    });

    _curveAnimation = CurvedAnimation(
      parent: _controller, //AnimationControllerを設定
      curve: Curves.bounceIn,
    );

使用例

class Sample extends StatefulWidget {
  @override
  _SampleState createState() => _SampleState();
}

class _SampleState extends State<Sample> with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation _curveAnimation;
  void _animationChange() {
    if (_controller.status == AnimationStatus.completed) {
      _controller.reverse();
    } else {
      _controller.forward();
    }
  }

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: Duration(seconds: 1),
      vsync: this,
    );

    _controller.addListener(() {
      setState(() {});
      print(_controller.value);
    });

    _curveAnimation = CurvedAnimation(
      parent: _controller,
      curve: Curves.bounceIn,
    );
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Center(
        child: Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        AnimatedBuilder(
          animation: _controller,
          builder: (BuildContext context, child) => child!,
          child: Transform.scale(
            scale: _curveAnimation.value,
            child: Container(
              height: 100,
              width: 100,
              color: Colors.blue,
            ),
          ),
        ),
        TextButton(
          onPressed: _animationChange,
          child: Text('Curve!'),
        )
      ],
    ));
  }
}

コメント

タイトルとURLをコピーしました