はじめに
FlutterのcrossAxisAlignmentとmainAxisAlignmentの違いについて、ColumnとRowで実際に変更しながら確認しまとめます。参考になれば幸いです。
使用するもの
- Column
- Row
Column
縦方向に並べる際に使用する。
基本となるコード
import 'package:flutter/material.dart';
class TopPage extends StatefulWidget {
const TopPage({Key? key}) : super(key: key);
@override
_TopPageState createState() => _TopPageState();
}
class _TopPageState extends State<TopPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Column'),
),
body: Column(
// 以下の2つをこれから変更していく
// mainAxisAlignment: MainAxisAlignment.start,
// crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
width: 200,
height: 200,
color: Colors.red,
),
Container(
width: 100,
height: 100,
color: Colors.yellow,
),
Container(
width: 50,
height: 50,
color: Colors.green,
),
Container(
width: 25,
height: 25,
color: Colors.blue,
),
],
),
);
}
}
これを元にして処理を加えていく
mainAxisAlignment
start
上に寄る。
center
中央にくる。
end
下に寄る。
spaceAround
縦方向の余白を端にも同じ分設ける。
spaceBetween
縦方向の余白を要素間のみ均等に設ける。
spaceEvenly
縦方向の余白を全て同じ分設ける。
crossAxisAlignment
start
左に寄る。
center
中央にくる。
end
右に寄る。
stretch
要素が画面横方向に伸びる。
Row
横方向に並べる際に使用する。
基本となるコード
class _TopPageState extends State<TopPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Row'),
),
body: Row(
// 以下の2つをこれから変更していく
// mainAxisAlignment: MainAxisAlignment.start,
// crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
width: 150,
height: 150,
color: Colors.red,
),
Container(
width: 100,
height: 100,
color: Colors.yellow,
),
Container(
width: 50,
height: 50,
color: Colors.green,
),
Container(
width: 25,
height: 25,
color: Colors.blue,
),
],
),
);
}
}
これを元にして処理を加えていく
mainAxisAlignment
start
center
end
spaceAround
spaceBetween
spaceEvenly
crossAxisAlignment
start
center
end
stretch
まとめ
- mainAxisAlignment
- それぞれの方向に影響を与える
- crossAxisAlignment
- 縦横反対の方向に影響を与える
おわりに
きちんと認識出来ていなかった部分があったので良い確認になりました!
ここまで読んでいただき、ありがとうございました。
何かありましたらコメントをお願いします。