[Flutter]AnimationControllerの使い方

Flutter

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

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

スポンサーリンク

使い方

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

準備

AnimationControllerを使うには、まずSingleTickerProviderStateMixinをStateで使えるようにします。

class _SampleState extends State<Sample> with SingleTickerProviderStateMixin {
  ・・・
}

これはAnimationControllerを初期化するために使うMixinです。

そして、変数を用意します。

late AnimationController _controller;

次に、initStateメソッドで、AnimationControllerを初期化します。

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

AnimationControllerの引数では、アニメーションの設定をすることが出来ます。

また、AnimationControllerのthisは、SingleTickerProviderStateMixinのものです。

これでアニメーションの初期化ができます。

最後に、disposeメソッドで、Widgetの非表示と共に、インスタンスを破棄するようにします。

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

これで準備完了です。

アニメーションを使うには?

プログラマー, プログラミング, コード, 仕事, コンピューター

アニメーションを使うには、TweenとAniamtedBuilderウェジェットを使います。

Tween

Tweenは、AnimationControllerで生成した値を使って、色やサイズなどの値を作ってくれるクラスです。

AnimationControllerが生成するのは、「0〜1」の値です。

Tweenは、これを色やサイズなどの値に変換してくれるのです。

Tweenを使うには、まず変数を用意します。

late Animation _colorAnimation;

そして、initStateメソッドで初期化をします。

_colorAnimation = ColorTween(
                                     begin: Colors.grey, //アニメーション前の値
                                     end: Colors.red //アニメーション後の値
                                 ) .animate(_controller);  // AnimationControllerの設定

ColorTweenの引数では生成する値の設定をします。

また、ColorTweenの後に、animateメソッドを呼びします。

このメソッドの引数に、AnimationControllerを指定します。

これで、controllerで生成した値を、Tweenで変換することが出来ます。

ここでは、Tweenとまとめていますが、実際には生成する値に応じたTweenクラスがあります。

例えば、色であったら「ColorTween」、サイズであったら「SizeTween」があります。

AnimatedBuilder

AnimatedBuilderは、AnimationControllerをウェジェットに反映するためのものです。

このウェジェットを使うことで、controllerでアニメーションをすることが出来るようになります。

AnimatedBuilder(
        animation: _controller, //コントローラの設定
        builder: (BuildContext context, Widget? child) {
           ・・・・
        }
);

引数「animation」でAnimationControllerの設定をします。

そして、引数「builder」で、アニメーションするウェジェットを返します。

「builder」のウェジェットで、AnimationControllerの操作をすれば、アニメーションをすることが出来るようになります。

使用例

AnimatedBuilder(
          animation: _controller, //コントローラの設定
          builder: (BuildContext context, Widget? child) {
            return IconButton(
              onPressed: () {
                if (_controller.status == AnimationStatus.dismissed) {
                  _controller.forward(); //アニメーション開始
                } else if (_controller.status == AnimationStatus.completed) {
                  _controller.reverse();//逆向きのアニメーション開始
                }
              },
              icon: Icon(Icons.favorite),
              color: _colorAnimation.value,//Tweenの値で色を変更
            );
          })

AnimatioControllerは、次のようなプロパティやメソッドを使うことで、アニメーションを操作することが出来ます。

  • valueプロパティ: 生成した値(Tweenでも同様)
  • statusプロパティ:アニメーションの状態(dismissedでアニメーション前、completedでアニメーション後)
  • forwardメソッド : アニメーションの開始
  • reverseメソッド:逆向きのアニメーションの開始
  • repeatメソッド : アニメーションを繰り返す

全体のコード

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

class _SampleState extends State<Sample> with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation _colorAnimation;

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

    _colorAnimation =
        ColorTween(begin: Colors.grey, end: Colors.red).animate(_controller);
  }

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

  @override
  Widget build(BuildContext context) {
    return Center(
      child: AnimatedBuilder(
          animation: _controller,
          builder: (BuildContext context, Widget? child) {
            return IconButton(
              onPressed: () {
                if (_controller.status == AnimationStatus.dismissed) {
                  _controller.forward();
                } else if (_controller.status == AnimationStatus.completed) {
                  _controller.reverse();
                }
              },
              icon: Icon(Icons.favorite),
              color: _colorAnimation.value,
            );
          }),
    );
  }
}

コメント

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