[Flutter]テキストの色を変えるアニメーション

Flutter

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

テキストの色を変えるアニメーションをする方法を紹介します。

スポンサーリンク

方法

bool isBlue = false;
  
@override
  Widget build(BuildContext context) {
    return Center(
        child: Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        AnimatedDefaultTextStyle(
          child: Text('Awesome Flutter!'),
          style: TextStyle(
            color: isBlue ? Colors.blue : Colors.red,
            fontSize: 56,
          ),
          duration: Duration(seconds: 1),
        ),
        TextButton(
          onPressed: () => setState(() => isBlue = !isBlue),
          child: Text('Change'),
        )
      ],
    ));
  }

テキストの色を変えるアニメーションをするには、「AnimatedDefaultTextStyle」を使います。

AnimatedDafaultTextStyleの引数「color」で、色を切り替えれば自動的にアニメーションがつきます。

アニメーションの長さは、「duration」で指定します。

        AnimatedDefaultTextStyle(
          child: Text('Awesome Flutter!'),
          style: TextStyle(
            color: isBlue ? Colors.blue : Colors.red, //色の切り替え
            fontSize: 56,
          ),
          duration: Duration(seconds: 1), //時間の設定
        ),

まとめ

テキストの色を変えるアニメーションをするには、AnimatedDefaultTextStyleを使います。

コメント

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