[Flutter] ColorTweenについて学ぼう

Flutterは、美しいUIを構築するための柔軟なツールセットを提供しています。Flutterには多くのアニメーションのオプションがありますが、その中でも特に便利なアニメーションクラスの1つが ColorTween です。 ColorTweenは、開始色と終了色を定義し、その間の色をスムーズに補間することができます。

この記事では、 ColorTweenを使ってFlutterアプリでアニメーションを作成する方法を紹介します。

目次

ColorTweenの使い方

ColorTweenを使用するには、2つの色を定義する必要があります。これらは beginend と呼ばれます。 たとえば、赤色から青色に徐々に変化するアニメーションを作成する場合、開始色は Colors.red 、終了色は Colors.blue に設定します。

ColorTween(
   begin: Colors.red,
   end: Colors.blue,
)

アニメーションサンプル

以下は、ColorTweenを使用して背景色を変更する簡単なアニメーションの例です。

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with TickerProviderStateMixin {
  late final AnimationController _controller;
  late final Animation<Color?> _animation;

  @override
  void initState() {
    super.initState();

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

    _animation = ColorTween(
      begin: Colors.red,
      end: Colors.blue,
    ).animate(_controller);

    _controller.repeat(reverse: true);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('ColorTween Animation')),
        body: Center(
          child: AnimatedBuilder(
            animation: _animation,
            builder: (context, child) {
              return Container(
                color: _animation.value,
                width: 200,
                height: 200,
              );
            },
          ),
        ),
      ),
    );
  }

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

この例では、 _controller_animation の2つの変数が作成されています。 _controllerAnimationController クラスのインスタンスで、アニメーションを制御するために使用されます。 _animationColorTween クラスのインスタンスで、アニメーションが変化する色を定義します。

initState メソッドでは、 _controller_animation の値が設定され、アニメーションが再生されます。 _controller.repeat(reverse: true) を呼び出すことで、アニメーションが無限に繰り返され、往復するようになります。

build メソッドでは、 AnimatedBuilder ウィジェットが使用されています。 AnimatedBuilder ウィジェットは、アニメーションを再生するために必要な BuildContext とアニメーションオブジェクトを受け取り、子ウィジェットを再描画する必要があるときに呼び出されます。 ここでは、 Container の背景色が _animation.value に設定され、ウィジェットの再描画が行われるたびにアニメーションが更新されます。

まとめ

ColorTween を使用すると、非常に簡単にウィジェットの背景色をアニメーション化することができます。この記事では、 ColorTween の使い方を紹介し、例を通して詳しく説明しました。 ColorTween を使用して、Flutterアプリで美しいアニメーションを作成することができるので、みなさん試してみてください!

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!
目次