Question #308EasyWidgets & UI

What is the purpose of the Expanded widget in Flutter?

#flutter#widget#layout

Answer

Overview

The

text
Expanded
widget makes a child of a
text
Row
,
text
Column
, or
text
Flex
take up all remaining available space along the main axis, after all non-flexible children have been sized.


Basic Usage

dart
Row(
  children: [
    Text('Label: '),        // Takes only the space it needs
    Expanded(
      child: TextField(),   // Takes ALL remaining width
    ),
  ],
)

How It Works

text
|---Row--------------------------------------------|
| [Text: 60px] | [Expanded fills remaining space→] |
|--------------------------------------------------|

In Column

dart
Column(
  children: [
    AppBar(), // Fixed height
    Expanded(
      child: ListView.builder(...), // Fills all remaining vertical space
    ),
    BottomNavigationBar(), // Fixed height
  ],
)

Using flex for Proportional Sizing

dart
Row(
  children: [
    Expanded(
      flex: 2,                           // Takes 2/3 of space
      child: Container(color: Colors.blue),
    ),
    Expanded(
      flex: 1,                           // Takes 1/3 of space
      child: Container(color: Colors.red),
    ),
  ],
)

Expanded vs Flexible

dart
// Expanded: child MUST fill all allocated space
Expanded(child: Container(color: Colors.blue))

// Flexible: child CAN be smaller than allocated space
Flexible(child: Container(width: 50, color: Colors.red))

Common Use Cases

Use CaseExample
TextField taking remaining row width
text
Row → [Label] + [Expanded(TextField)]
Body filling screen between AppBar & BottomBar
text
Column → [AppBar] + [Expanded(body)] + [BottomBar]
Equal-width columns
text
Row → [Expanded] + [Expanded]
2:1 ratio layout
text
Row → [Expanded(flex:2)] + [Expanded(flex:1)]

Note:

text
Expanded
is just shorthand for
text
Flexible(fit: FlexFit.tight)
. It always forces the child to fill its allocated space.