Flutter: Expanding Space with Expanded Widget
Flutter Expanded Widget - Expanding Space
Expanded expands a widget inside a Row or Column to fill all available empty space. Similar to Spacer, but the important difference is that it can contain visible content.
What is Expanded?
Expanded expands its child in Flex containers (Row, Column) to fill the available empty space. While Spacer is used for empty space, Expanded is used for content.
Live Demo: Expanded Widget Examples
Try Expanded and flex usage interactively:
Basic Usage
Expanded in Row
Row(
children: [
Container(width: 50, color: Colors.red),
Expanded(
child: Container(color: Colors.blue, child: Text('I expanded')),
),
Container(width: 50, color: Colors.green),
],
)The blue container fills all the space remaining after the red and green containers.
Expanded in Column
Column(
children: [
Container(height: 50, color: Colors.red),
Expanded(
child: Container(color: Colors.blue, child: Text('I expanded')),
),
Container(height: 50, color: Colors.green),
],
)The blue container fills all the remaining space vertically.
Flex Parameter
When multiple Expanded widgets are used, you can determine how the space is shared with the flex parameter:
Row(
children: [
Expanded(
flex: 1,
child: Container(color: Colors.red, child: Text('1 unit')),
),
Expanded(
flex: 2,
child: Container(color: Colors.blue, child: Text('2 units')),
),
Expanded(
flex: 1,
child: Container(color: Colors.green, child: Text('1 unit')),
),
],
)Total flex: 1+2+1 = 4
- Red: 1/4 (25%) space
- Blue: 2/4 (50%) space
- Green: 1/4 (25%) space
Expanded vs Flexible
Expanded is actually the same as Flexible(fit: FlexFit.tight):
Expanded
Row(
children: [
Expanded(
child: Container(color: Colors.blue),
),
],
)Flexible (Equivalent)
Row(
children: [
Flexible(
fit: FlexFit.tight,
child: Container(color: Colors.blue),
),
],
)Difference:
Expanded: Always fills all space (tight)Flexible: Can optionally expand (loose)
When to Use?
Use Expanded:
- When you want flexible space inside Row/Column
- To prevent overflow errors
- When creating responsive layouts
- When you want to scale according to screen size
Summary
Expanded:
- Expands widget inside Row or Column
- Fills available empty space
- Makes proportional sharing with
flexparameter - Default flex value is 1
- Used for content (Spacer for empty space)
- Prevents overflow errors
- Equivalent to
Flexible(fit: FlexFit.tight)
Expanded is one of the building blocks of creating responsive and flexible layouts in Flutter.