😺
[Flutter]Stackウィジェットの個人的まとめ
Stack ウィジェットの使い方
(前提:widgetとはクラスです。Stack class
と呼ぶのがオブジェクト指向的には良いのかなとか個人的に思っている。)
Stack : ボックス(親要素)の端を基準にして子を配置するためのウィジェット。
(position:ralative/absolute的な使い方ができる感じ。)
使える主なプロパティ(引数)と、Stackで使えるWidgetを挙げる。
-
children
(プロパティ) -
alignment
(プロパティ)とAlign
(Widget) -
Positioned
(Widget。並べた小要素をPositionedでラップして使える)
children[要素を配置する]
main.dart
Stack(
children: <Widget>[
Container(
color: Colors.green,
height: 150,
width: 150,
),
Container(
color: Colors.blue,
height: 75,
width: 75,
),
Container(
color: Colors.red,
height: 50,
width: 50,
),
],
)
Point
- children:(引数)の中に要素を入れる
- 左上を原点にして入れていく
- コード順に下層に配置されるので今回の例では1番目が最下層、3番目が最上層になる
alignment/Align[子要素の位置を指定する(Centerとか)]
- alignmentの場合(「一括指定」)
main.dart
Stack(
alignment: AlignmentDirectional.center, // 子要素を中央に配置する
children: <Widget>[
Container(
color: Colors.green,
height: 150,
width: 150,
),
Container(
color: Colors.blue,
height: 75,
width: 75,
),
Container(
color: Colors.red,
height: 50,
width: 50,
),
],
)
Point
-
alignment:
は子要素の配置位置を一括で操作できる。 -
alignment: AlignmentDirectional.center
って感じ。
-
Alignの場合(「個別指定」)
main.dart
Stack(
alignment: AlignmentDirectional.center,
children: <Widget>[
Container(
color: Colors.green,
height: 150,
width: 150,
),
Container(
color: Colors.blue,
height: 75,
width: 75,
)
-----------------------------------
// Point↓↓↓↓↓↓↓↓↓
Align( // 赤のコンテナだけを右下に配置する
alignment: Alignment.bottomRight,
child: Container(
color: Colors.red,
height: 50,
width: 50,
),
),
],
)
Point
-
Align()
は子要素の配置位置を個別に操作できる。 -
Align(alignment: Alignment.bottomRight, child:~),
って感じ
Potitioned[子要素の位置を細かく指定する(left:30 とか)]
main.dart
Stack(
children: [
-----------------------
↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
Positioned( // 緑のコンテナだけを親の左上に配置する
top: 0, // Point! 数値指定ができ、またleft,topといった四方からの指定も可能
left: 0,
child: Container(
color: Colors.green,
height: 150,
width: 150,
),
),
-----------------------
Positioned( // 青のコンテナだけを親上枠から 10px,右枠から 10px のところに配置する
top: 10,
right: 10,
child: Container(
color: Colors.blue,
height: 75,
width: 75,
),
),
// PositionedとAlginは混在しててもOK。
Align( // 赤のコンテナだけを右下に配置する
alignment: Alignment.bottomRight,
child: Container(
color: Colors.red,
height: 50,
width: 50,
),
),
],
)
Point
-
Positioned()
は子要素の配置位置を個別に、数値で操作できる。
(left:20
的な感じで細かく数値指定できるところが強い) -
Align(alignment: Alignment.bottomRight、children:~),
って感じ
(この辺に関してはAlign
Widgetの使い方解説してる感じではあるが。) -
Positioned
とAlgin
は混在しててもOK
まとめ
- chidrenで子要素配置
- Positionedは細かい数値指定
- Align/alignmentは並びの指定
って感じかな
以上です。間違えが見つかり次第、或いは知識がアップデートされ次第改訂していきます。🙏
Discussion