すらぼうの開発ノート

モバイルアプリエンジニアのメモ

【Flutter】Wrapウィジェットで折り返して並べるUIを作る

アイテムを水平方向に並べた際、折り返して表示をしたい場合がある。

このようなケースではWrapウィジェットを用いることで、 画面に収まらないアイテムを折り返して表示してくれる。

本エントリではWrapウィジェットの使い方について説明する。

Wrapウィジェットとは

api.flutter.dev

childrenとして渡されたウィジェットを並べて表示するレイアウト系のウィジェット。 並べた時に画面からはみ出ないように折り返して次の行または列で表示をする。

次にWrapウィジェットで使用頻度の高いプロパティを説明する。 Wrapウィジェット内に表示するウィジェットは次のChipを10個保有するリストとする。

  List<Widget> _items = [
    Chip(label: Text("chip 1")),
    Chip(label: Text("chip 2")),
    Chip(label: Text("chip 3")),
    Chip(label: Text("chip 4")),
    Chip(label: Text("chip 5")),
    Chip(label: Text("chip 6")),
    Chip(label: Text("chip 7")),
    Chip(label: Text("chip 8")),
    Chip(label: Text("chip 9")),
    Chip(label: Text("chip 10")),
  ];

よく使うプロパティ

children ※必須

Wrapウィジェットの範囲内で並べたいウィジェットを指定する。 ソースコードとシミュレーター上の表示は次の通り。

Center(
        child: Wrap(
          children: _items,
        ),
      ),

children

spacing

ウィジェット間の隙間を設定する。

Center(
        child: Wrap(
          spacing: 10,
          children: _items,
        ),
      ),

spacing

runSpacing

ウィジェットを並べる方向と垂直の方向の隙間を設定する。 画像の例だと行間の隙間を100と設定している。

Center(
        child: Wrap(
          runSpacing: 100,
          children: _items,
        ),
      ),

runSpacing

direction

ウィジェットを並べる方向を設定する。 デフォルトは水平方向(horizontal)。

Center(
        child: Wrap(
          direction: Axis.vertical,
          children: _items,
        ),
      ),

direction

alignment

ウィジェットの並べ方を設定する。 具体的には、余白をどのように扱うかを指定する。

alignmentには次のようなウィジェットを渡すことができる。

  • WrapAlignment.center
  • WrapAlignment.end
  • WrapAlignment.spaceAround
  • WrapAlignment.spaceBetween
  • WrapAlignment.spaceEvenly
  • WrapAlignment.start

ソースコードは次のようになる。

Wrap(
    alignment: WrapAlignment.center,
    children: _items,
),

それぞれのウィジェットを渡した際の表示は次のようになる。

center

end

spaceAround

spaceBetween

spaceEvenly

start