すらぼうの開発ノート

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

【Flutter】Spacerの使い方


Spacer

サイズを指定できるスペースを作成するウィジェットRowやColumnなどのFlexウィジェットの子ウィジェットとして使用する。

スペースはFlexウィジェットのmain axis方向に作成される。 (Column:垂直方向、Row:水平方向)

api.flutter.dev


使い方

基本形

Column内で使用する場合。

Column(
  children: [
    ... ,
    Spacer(flex: ... /* スペースの割合 */),
    ...
  ],
),

これで可能な限りのスペースが挿入される。

以降で例を示しながら説明する。

Spacerが1つのケース

Spacer()記入前の状態は以下とする。

Container(
  padding: const EdgeInsets.all(100.0),
  child: Column(
    children: [
      Container(
        height: 50,
        color: Colors.red,
      ),
      Container(
        height: 50,
        color: Colors.blue,
      ),
    ],
  ),
);

Column内にSpacerを記入すると 表示は次のようになる。

Container(
  padding: const EdgeInsets.all(100.0),
  child: Column(
    children: [
      Container(
        height: 50,
        color: Colors.red,
      ),
      Spacer(),
      Container(
        height: 50,
        color: Colors.blue,
      ),
    ],
  ),
);

Spacerが2つ以上のケース

Spacer()記入前の状態は以下とする。

Container(
      padding: const EdgeInsets.all(100.0),
      child: Column(
        children: [
          Container(
            height: 50,
            color: Colors.red,
          ),
          Container(
            height: 50,
            color: Colors.blue,
          ),
          Container(
            height: 50,
            color: Colors.green,
          ),
        ],
      ),
    );

Column内にSpacerを記入すると 表示は次のようになる。

Container(
  padding: const EdgeInsets.all(100.0),
  child: Column(
    children: [
      Container(
        height: 50,
        color: Colors.red,
      ),
      Spacer(
        flex: 1 /* */,
      ),
      Container(
        height: 50,
        color: Colors.blue,
      ),
      Spacer(
        flex: 3,
      ),
      Container(
        height: 50,
        color: Colors.green,
      ),
    ],
  ),
);

画像の通り、flexプロパティに指定した値が挿入されるスペースのサイズ比になる。 上記の例では

赤青間スペース : 青緑間スペース = 1 : 3

となる。