LoginSignup
117
58

Flutter: MainAxisAlignmentを理解する

Last updated at Posted at 2019-08-19

Flutterでレイアウトを組み立てる際、ColumnとRowはほぼ必ず使う。
そのColumnとRowでmainAxisAlignmentを指定するわけだが、違いがよく分からないので整理してみた。

環境

Flutter 1.7.8+hotfix.4 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 20e59316b8 (4 weeks ago) • 2019-07-18 20:04:33 -0700
Engine • revision fee001c93f
Tools • Dart 2.4.0

使用レイアウトコード

縦にテキストが3行並んでるだけのシンプルなレイアウト

Center(
  child: Column(
    mainAxisAlignment: MainAxisAlignment.start, // <= 今回のターゲット
    children: <Widget>[
      Container(
        height: 100,
        color: Colors.orange,
        child: Text(
          'First',
          style: Theme.of(context).textTheme.display1,
        ),
      ),
      Container(
        height: 100,
        color: Colors.green,
        child: Text(
          'Second',
          style: Theme.of(context).textTheme.display1,
        ),
      ),
      Container(
        height: 100,
        color: Colors.blue,
        child: Text(
          'Third',
          style: Theme.of(context).textTheme.display1,
        ),
      ),
    ],
  ),
),

画面イメージ
2019-08-18-08-56-39.png

今回は、Columnに設置したMainAxisAlignmentの値を変更し、レイアウトへの表示を確認して学んでいく。

MainAxisAlignmentとは

公式ドキュメントによると
https://api.flutter.dev/flutter/rendering/MainAxisAlignment-class.html

フレックスレイアウトで子を主軸に沿って配置する方法。

この説明を読んでも「?」となるが、主軸(メイン方向)というのがキモで、
Columnなら縦、Rowなら横
が主軸の方向となる。
なぜなら、Columnは子レイアウトを縦方向に並べ、Rowは横方向に子を並べるため。
図での説明を見ると分かりやすい)

あと、ソースを見ても分かるが、MainAxisAlignmentはただのenumだった。

MainAxisAlignmentの種類と挙動

start

メイン方向の開始位置に配置されれる。

2019-08-18-08-56-39.png

end

メイン方向の終了位置に配置されれる。

2019-08-19-14-45-23.png

center

メイン方向の中央位置に配置されれる。
2019-08-19-14-48-28.png

spaceBetween

子たちの間に空きスペースを均等に置く。
開始/終了にはスペースを設けない。

2019-08-19-14-49-56.png

spaceAround

並べた子の間に空きスペースを均等に配置する。

スクリーンショット 2021-01-28 21.23.34.png

spaceEvenly

開始、終了、子の間に空きスペースを均等に配置する。

2019-08-19-14-51-29.png

コード置き場

実装に使用したリポジトリ
https://github.com/ikemura23/flutter_lab/tree/MainAxisAlignment

117
58
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
117
58