FlutterでHTMLの <div> タグのような機能を持つウィジェットはいくつかあります。
1. Container(基本のDiv)
最も基本的な <div> の代わりになるのが Container です。
Container(
width: 200,
height: 100,
color: Colors.blue,
child: Center(
child: Text("Container", style: TextStyle(color: Colors.white)),
),
)
- CSSの div に最も近い要素
- 幅・高さ・背景色などを指定できる
2. SizedBox(幅・高さだけ指定)
CSSの <div style=”width: 100px; height: 100px;”> のように、幅と高さだけ指定するなら SizedBox が便利です。
SizedBox(
width: 100,
height: 100,
child: Center(child: Text("SizedBox")),
)
- 背景色なしのシンプルなブロックを作れる
3. Column / Row(複数の要素を並べる)
<div> で要素を縦・横に並べるなら Column や Row を使います。
Column(
children: [
Text("上のテキスト"),
Container(
width: 100,
height: 50,
color: Colors.blue,
child: Center(child: Text("青いボックス")),
),
],
)
- 縦方向に要素を並べる(横方向なら Row)
4. Stack(重ねる)
<div> の position: absolute; に相当するのが Stack です。
Stack(
children: [
Container(width: 200, height: 100, color: Colors.blue),
Positioned(
left: 50,
top: 20,
child: Text("重ねたテキスト", style: TextStyle(color: Colors.white)),
),
],
)
- 要素を自由に配置できる
5. Expanded(親の幅いっぱいにする)
CSSの width: 100% に相当するのが Expanded です。
Row(
children: [
Expanded(child: Container(height: 50, color: Colors.red)),
Expanded(child: Container(height: 50, color: Colors.blue)),
],
)
- 親の幅いっぱいに広げる(flex-grow: 1 のような動き)
6. Flexible(割合で幅を調整)
CSSの flex: 2 1 auto; のような動きをするのが Flexible です。
Row(
children: [
Flexible(flex: 2, child: Container(height: 50, color: Colors.red)),
Flexible(flex: 1, child: Container(height: 50, color: Colors.blue)),
],
)
- 要素の幅を割合で調整できる
結論
目的 Flutterのウィジェット
<div> の基本機能 | Container |
サイズのみ指定 | SizedBox |
要素を縦に並べる | Column |
要素を横に並べる | Row |
要素を重ねる | Stack |
幅を親に合わせる (width: 100%) | Expanded |
幅の割合を調整 (flex) | Flexible |
Flutterでは Container が最も <div> に近いが、レイアウトに応じて Column / Row / Stack も活用するのがポイント
コメントを残す