はじめに
タイトルのとおり,ColumnやRowに指定するMainAxisAlignmentのレイアウトがいつも分からなくなるので整理します。
(特にspaceBetween
, spaceAround
, spaceEvenly
これらの違いは整列アイテムの外側スペースのサイズが違う)
レイアウト
MainAxisAlignment | 間隔 | 外側 |
---|---|---|
start | なし | 整列開始のサイドはなし |
end | なし | 整列開始の逆サイドはなし |
center | なし | 両サイドは同一スペース |
spaceBetween | 等間隔 | なし |
spaceAround | 等間隔 | 両サイドにアイテム間隔の半分スペース |
spaceEvenly | 等間隔 | 両サイドにアイテム間隔と同等スペース |
サンプルコード
import 'package:flutter/material.dart';
final List<Widget> items = [
Colors.black12,
Colors.black26,
Colors.black38,
Colors.black45,
]
.map(
(e) => ColoredBox(
color: e,
child: const SizedBox(
width: 40,
height: 50,
child: Placeholder(),
),
),
)
.toList();
class MainAxisAlignmentView extends StatelessWidget {
const MainAxisAlignmentView({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('MainAxisAlignment Sample'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: const [
_MainAxisAlignmentView(
mainAxisAlignment: MainAxisAlignment.start,
),
_MainAxisAlignmentView(
mainAxisAlignment: MainAxisAlignment.end,
),
_MainAxisAlignmentView(
mainAxisAlignment: MainAxisAlignment.center,
),
_MainAxisAlignmentView(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
),
_MainAxisAlignmentView(
mainAxisAlignment: MainAxisAlignment.spaceAround,
),
_MainAxisAlignmentView(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
),
],
),
);
}
}
class _MainAxisAlignmentView extends StatelessWidget {
const _MainAxisAlignmentView({
required this.mainAxisAlignment,
});
final MainAxisAlignment mainAxisAlignment;
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.all(4.0),
child: Text(
'MainAxisAlignment.${mainAxisAlignment.name}',
style: Theme.of(context).textTheme.bodyLarge,
),
),
Row(
mainAxisAlignment: mainAxisAlignment,
children: items,
),
],
);
}
}