世界最大級のオンライン学習サービス「Udemy」のセール状況はこちら

【Flutter】CrossAxisAlignment.centerが効かない時の対処法

こんにちは、フラメルです。

今回はColumnRowなどでCrossAxisAlignment.centerを使用しても中央に表示されない場合の対処法を紹介します。

目次

CrossAxisAlignment.centerがなぜ効かないのか?

下記コードのようにColumnの子要素が全て横幅が同じ場合、CrossAxisAlignment.centerを使用しても上画像のように左側に表示されてしまいます。

Column(
  crossAxisAlignment: CrossAxisAlignment.center,
  children: [
    Container(
      width: 150,
      height: 150,
      color: Colors.red,
    ),
    Container(
      width: 150,
      height: 150,
      color: Colors.yellow,
    ),
    Container(
      width: 150,
      height: 150,
      color: Colors.blue,
    )
  ],
),

Columnの子要素のサイズが異なる場合

次にColumnの子要素の横幅が一部異なる場合、CrossAxisAlignment.centerを使用すると横幅が一番大きな子要素に対して他の子要素が中央に表示されます。

よって子要素のサイズを横幅いっぱいにすることで子要素を中央に表示できます。

対処法1:ColumnをSizedBoxで横幅いっぱいに広げる

先ほど解説したようにCrossAxisAlignment.centerは子要素のサイズに左右されるので、下記コードのように子要素にSizedBoxを使用しwidthdouble.infinityで横幅いっぱいにしてあげることで問題は解消します。

Column(
  crossAxisAlignment: CrossAxisAlignment.center,
  children: [
    SizedBox(
      width: double.infinity,
    ),
    Container(
      width: 150,
      height: 150,
      color: Colors.red,
    ),
    Container(
      width: 150,
      height: 150,
      color: Colors.yellow,
    ),
    Container(
      width: 150,
      height: 150,
      color: Colors.blue,
    )
  ],
),

対処法2: Centerで中央に表示

別の対処法としてCrossAxisAlignment.centerを使用せず、ColumnCenterでラップして中央に表示させる方法があります。

Center(
  child: Column(
    children: [
      Container(
        width: 150,
        height: 150,
        color: Colors.red,
      ),
      Container(
        width: 150,
        height: 150,
        color: Colors.yellow,
      ),
      Container(
        width: 150,
        height: 150,
        color: Colors.blue,
      )
    ],
  ),
),

以上です。

目次