FlutterでHTMLの <div> タグのような機能を持つウィジェットはいくつかあります。
最も基本的な <div> の代わりになるのが Container です。
Container(
width: 200,
height: 100,
color: Colors.blue,
child: Center(
child: Text("Container", style: TextStyle(color: Colors.white)),
),
)
CSSの <div style=”width: 100px; height: 100px;”> のように、幅と高さだけ指定するなら SizedBox が便利です。
SizedBox(
width: 100,
height: 100,
child: Center(child: Text("SizedBox")),
)
<div> で要素を縦・横に並べるなら Column や Row を使います。
Column(
children: [
Text("上のテキスト"),
Container(
width: 100,
height: 50,
color: Colors.blue,
child: Center(child: Text("青いボックス")),
),
],
)
<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)),
),
],
)
CSSの width: 100% に相当するのが Expanded です。
Row(
children: [
Expanded(child: Container(height: 50, color: Colors.red)),
Expanded(child: Container(height: 50, color: Colors.blue)),
],
)
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 も活用するのがポイント