今回は「Alignment」の基本的な使い方について紹介します。
Alignmentを使えば、Containerなどの親ウィジェットに対してchild Widgetの設置する位置を指定できます!
目次
Alignmentのコンストラクタ

コンストラクタでchild Widgetが設置される位置を指定します。親ウィジェット内部の左上に設置したい場合は「Alignment(-1, -1)」となります。
Alignment(x, y)



Alignmentの書き方には、Containerなどの親ウィジェット内で使用する方法と、Alignと併用する方法の2種類あります。
親ウィジェット内で使用する場合(Containerが親)
//ソース(左の画像)
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Flutter"),
),
body: Center(
child: Container(
height: 200.0,
width: 200.0,
color: Colors.yellow,
alignment: const Alignment(-1, -1),
child: const Text("Hello World"),
),
),
),
);
}
Alignで使用する場合
//ソース Alignで使用(左の画像)
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text("Flutter"),
),
body: Center(
child: Container(
height: 200.0,
width: 200.0,
color: Colors.yellow,
child: const Align(
alignment: Alignment(-1, -1),
child: Text("Hello World"),
),
),
),
),
);
}
どちらの書き方でも大丈夫です。
コンストラクタを使用しない方法



定数(Constants)を使用して位置を指定することもできます。
中央:Alignment.center = Alignment(0.0, 0.0)
左:Alignment.centerLeft = Alignment(-1.0, 0.0)
上:Alignment.topCenter = Alignment(0.0, -1.0)
右:Alignment.centerRight = Alignment(1.0, 0.0)
下:Alignment.bottomCenter = Alignment(0.0, 1.0)
左上:Alignment.topLeft = Alignment(-1.0, -1.0)
右上:Alignment.topRight = Alignment(-1.0, 1.0)
左下:Alignment.bottomLeft = Alignment(1.0, -1.0)
右下:Alignment.bottomRight = Alignment(1.0, 1.0)
以上です。