Back to quest
Flutter Widgets BasicLevel 7 / 7

Expanded & Flexible

Manage responsive layouts and dynamic sizing within Columns and Rows.

Expanded and Flexible widgets allow a child of a Row, Column, or Flex to expand to fill the available space in the main axis (e.g., horizontally for a Row or vertically for a Column).

Expanded Widget

Forces the child to fill the available space. If multiple children are expanded, the available space is divided among them.

Filling Remaining Space

example.dart
1 
2Row(
3 children: [
4 Container(width: 50, color: Colors.blue),
5 Expanded(
6 child: Container(color: Colors.green), // Fills remaining width
7 ),
8 Container(width: 50, color: Colors.red),
9 ],
10)
11

HintThe blue and red boxes take 50 width each. The green box expands to fill all remaining horizontal space.

Using Flex Factor

example.dart
1 
2Row(
3 children: [
4 Expanded(
5 flex: 2, // Takes twice the space
6 child: Container(color: Colors.blue),
7 ),
8 Expanded(
9 flex: 1, // Takes 1x space
10 child: Container(color: Colors.red),
11 ),
12 ],
13)
14

HintThe blue container takes up 2/3 of the space, while the red container takes 1/3.

Flexible Widget

Provides the flexibility for a child to resize. It uses a flex factor but doesn't force the child to fill the space if fit: FlexFit.loose is used.

Loose Fit (Wrap Content)

example.dart
1 
2Row(
3 children: [
4 Flexible(
5 fit: FlexFit.loose, // Only takes needed space, but can shrink
6 child: Container(
7 color: Colors.purple,
8 child: Text('Short Text'),
9 ),
10 ),
11 Expanded(child: Container(color: Colors.orange)),
12 ],
13)
14

HintThe purple container takes only the space needed for its text. The orange container fills the rest.

Loot collected

Key takeaways
  • Expanded forces a child to fill the available space.
  • Flexible allows a child to resize but respects its intrinsic size if FlexFit.loose is used.
  • Use the flex property to control the proportion of space each child receives.
Party chat

Comments