coiai Logo

This article is an English translation of the original Japanese post. Read the Japanese original →

[Flutter] The Widgets That Play the Role of a Div Tag on the Web

January 30, 2025

Categories: Flutter

[Flutter] The Widgets That Play the Role of a Div Tag on the Web

Flutter has several widgets that play a role similar to HTML's <div> tag.

1. Container (the basic Div)

Container is the most basic stand-in for <div>.

Container(

  width: 200,

  height: 100,

  color: Colors.blue,

  child: Center(

    child: Text("Container", style: TextStyle(color: Colors.white)),

  ),

)

2. SizedBox (specifying only width and height)

If you just want to specify width and height, like CSS's <div style=”width: 100px; height: 100px;”>, SizedBox is handy.

SizedBox(

  width: 100,

  height: 100,

  child: Center(child: Text("SizedBox")),

)

3. Column / Row (arranging multiple elements)

If you want to arrange elements vertically or horizontally, the way you might with nested <div>s, use Column or Row.

Column(

  children: [

    Text("上のテキスト"),

    Container(

      width: 100,

      height: 50,

      color: Colors.blue,

      child: Center(child: Text("青いボックス")),

    ),

  ],

)

4. Stack (overlapping elements)

Stack is the equivalent of <div>'s position: absolute;.

Stack(

  children: [

    Container(width: 200, height: 100, color: Colors.blue),

    Positioned(

      left: 50,

      top: 20,

      child: Text("重ねたテキスト", style: TextStyle(color: Colors.white)),

    ),

  ],

)

5. Expanded (filling the parent's full width)

Expanded is the equivalent of CSS's width: 100%.

Row(

  children: [

    Expanded(child: Container(height: 50, color: Colors.red)),

    Expanded(child: Container(height: 50, color: Colors.blue)),

  ],

)

6. Flexible (adjusting width by ratio)

Flexible behaves like CSS's flex: 2 1 auto;.

Row(

  children: [

    Flexible(flex: 2, child: Container(height: 50, color: Colors.red)),

    Flexible(flex: 1, child: Container(height: 50, color: Colors.blue)),

  ],

)

Conclusion

Purpose Flutter widget

Basic <div> functionalityContainer
Specifying size onlySizedBox
Arranging elements verticallyColumn
Arranging elements horizontallyRow
Overlapping elementsStack
Matching the parent's width (width: 100%)Expanded
Adjusting width by ratio (flex)Flexible

In Flutter, Container is the closest match to <div>, but the key is to also make use of Column / Row / Stack depending on your layout.