【Flutter】Widgetを横並び・縦並びにしてレイアウトを整える〔Column/Row〕

Flutter
 

最終的な実現イメージ

以下のように、ボタンが縦並び(Column)、横並び(Row)に整理されているレイアウトを
作成したい時の実装方法を紹介します。

実現ソースとしてはColumnやRowを入れ子(Nested)にしていき実装するイメージですね。

実装ソース

以下のようなWidgetを作成することで実装できます。

実装ポイントは3つです。

  • ColumnとRowを入れ子にして縦横の並びを実装する
  • 全体的な並び位置をMainAxisAlignmentで整える
  • 繰り返し配置するボタンを抽出(Extract)してコードを整える

それぞれを赤・青・黄でハイライトしました。

以下にて詳細の実装について説明していきます。

class ArrangeButtons extends StatelessWidget {
  const ArrangeButtons({
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            weekButton('今 週'),
            weekButton('来 週'),
          ],
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            weekButton('2週間後'),
            weekButton('それ以降'),
          ],
        ),
      ],
    );
  }

  Expanded weekButton(String buttonText) {
    return Expanded(
      child: Padding(
        padding: const EdgeInsets.all(2.0),
        child: ElevatedButton(
          onPressed: () {},
          child: Text(buttonText),
        ),
      ),
    );
  }
}

ColumnとRowを入れ子にして縦横の並びを実装する

親WidgetであるColumnは2つのchildrenを持たせます。

そのchildrenは子WidgetであるRowです。

子WidgetであるRowはさらに2つのWidgetを持たせます。

そのchildrenに縦横並びにしたいWidgetを配置してあげることでレイアウトを整えることができます。

ただ、これを配置しただけでは全体的に左によったレイアウトができると思います。
(ここで登場するのがMainAxisAlignment)

Column(
  children: [
    Row(
      children: [
        【Widget1】,
        【Widget2】,
      ],
    ),
    Row(
      children: [
        【Widget3】,
        【Widget4】,
      ],
    ),
  ],
);

全体的な並び位置をMainAxisAlignmentで整える

RowやColumnを定義しただけでは残念ながら、左に寄ったレイアウトができると思います。

ここで、MainAxisAlignmentにて全体的な並び位置を定義してあげます。

今回はRow側(横並び側)に対してchildren内のWidgetの感覚を開けて中央揃え(spaceEvenly)
にしてあげます。

Row(
  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
  children: [
    【Widget1】,
    【Widget2】,
  ],
),

MainAxisAlignmentには他にさまざまな配置オプション(正確にはenum)があるので、
『Flutter mainaxisalignment』でググって画像検索してみるとイメージが湧くと思います。

繰り返し配置するボタンを抽出(Extract)してコードを整える

このままでもいちよう動きますが、4個配置しているボタンのWidgetを
全てハードコーディングしていると、入れ子の部分が見にくくなると思います。

そこでボタンのソースだけをメソッド化しておき、見やすさを向上させます。

Flutterは何と便利なことに切り出したしWidgetを選択して、「Extract Method」を押下するだけで
勝手に切り出してくれます!!!!!!(Reactしかやったことなかったから、ほんとに便利)

詳しくは以下を参照ください(動画で紹介しています)

(略)
          children: [
            weekButton('今 週'),
            weekButton('来 週'),
          ],
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            weekButton('2週間後'),
            weekButton('それ以降'),
          ],
        ),
      ],
    );
  }

  Expanded weekButton(String buttonText) {
    return Expanded(
      child: Padding(
        padding: const EdgeInsets.all(2.0),
        child: ElevatedButton(
          onPressed: () {},
          child: Text(buttonText),
        ),
      ),
    );
  }
}

コメント

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