[Flutter]サイズを変えるアニメーションをするには?

Flutter

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

サイズを変えるアニメーションをする方法を紹介します。

スポンサーリンク

方法

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

サイズを変えるアニメーションをするには、AnimatedContainerを使います。

まず、サイズを変えるアニメーションをするウェジェットを「AnimatedContainer」の「child」に指定します。

次に、AnimatedContainerの引数「duration」にアニメーションの時間を指定します。

そして、AnimatedContainerの「width」で横幅、「height」で高さが切り替わるようにします。

AnimatedContainer(
  duration: Duration(seconds: /*時間*/),
  height: /*サイズの切り替え*/,
  width: /*サイズの切り替え*/,
  child : Widget(),
)

AnimatedContainerは、サイズが変わると自動でアニメーションをしてくれます。

以下は、使用例です。

bool _isExpand = false;
  
@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            AnimatedContainer(
              duration: Duration(seconds: 2),
              height: _isExpand ? 200 : 100,
              width: _isExpand ? 200 : 100,
              curve: Curves.bounceInOut,
              color: Colors.pink,
              child: Center(
                child: Text('Hello!'),
              ),
            ),
            ElevatedButton(
              onPressed: () {
                setState(() {
                  _isExpand = !_isExpand;
                });
              },
              child: Text('Change Size'),
            )
          ],
        ),
      ),
    );
  }

AnimatedSizeを使うことで、同じようにサイズを変えるアニメーションをすることが出来ます。

ですが、AnimatedSizeの場合は、1方向のみのアニメーションになります。

なので、AnimatedContainerの方が使いやすいです。

コメント

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