Sub topic 6
Controlling How Much Space a Row or Column Takes
This chapter assumes you know basic Dart syntax, StatelessWidget, and the build method. It focuses on MainAxisSize, which controls whether a Row or Column takes all available space or only the space its children need.
The main axis
A Row lays out children horizontally. Its main axis runs from left to right.
A Column lays out children vertically. Its main axis runs from top to bottom.
MainAxisSize controls the size of the Row or Column along that main axis.
| Value | Meaning |
|---|---|
| `MainAxisSize.max` | Take as much main-axis space as the parent allows |
| `MainAxisSize.min` | Take only enough main-axis space for the children |
The default is MainAxisSize.max. Therefore, a Column usually expands to the available height, and a Row usually expands to the available width.
`MainAxisSize.max` and `MainAxisSize.min`
The following Column takes the maximum available height. Its children remain at the top because MainAxisAlignment.start is used.
Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.start,
children: const [
Text('Account'),
Text('Signed in'),
],
)Changing the value to MainAxisSize.min makes the Column wrap its content along its vertical main axis:
Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: const [
Text('Account'),
SizedBox(height: 8),
Text('Signed in'),
],
)This Column is only as tall as the two text widgets and the gap between them. Its width is still controlled by the cross-axis constraints and CrossAxisAlignment.
The same rule applies to a Row:
Row(
mainAxisSize: MainAxisSize.min,
children: const [
Icon(Icons.check),
SizedBox(width: 8),
Text('Completed'),
],
)The Row becomes only as wide as its icon, gap, and text require.
How constraints affect the result
Flutter layout follows this general process:
- The parent sends constraints to the
RoworColumn. - The flex widget lays out its children.
- The flex widget chooses a size allowed by those constraints.
- The parent positions the finished widget.
MainAxisSize.min does not mean “ignore the parent.” The widget still cannot exceed the maximum size in its constraints. Likewise, MainAxisSize.max cannot create space that the parent did not provide.
Choosing the right value
Use MainAxisSize.min when a group should wrap its content, such as a label-and-icon chip, a compact card section, or a dialog title.
Use MainAxisSize.max when the layout should fill its available axis, such as a screen column or a toolbar row. It also gives MainAxisAlignment.spaceBetween, center, and similar values room to distribute children.
Exercise
A Column contains two short Text widgets inside a tall parent. Which MainAxisSize value makes the Column wrap the text instead of filling the parent's height?
Show answer
MainAxisSize.min.