Sub topic 5
Aligning Children with MainAxisAlignment and CrossAxisAlignment
Assume you know basic Dart syntax, StatelessWidget, and the build method. This chapter focuses on how Row and Column position their children after sizing them.
The two layout axes
A Row lays out children horizontally. Its main axis runs from left to right, and its cross axis runs from top to bottom.
A Column lays out children vertically. Its main axis runs from top to bottom, and its cross axis runs from left to right.
MainAxisAlignment controls positions along the main axis. CrossAxisAlignment controls positions across the cross axis.
MainAxisAlignment
The mainAxisAlignment property distributes any extra space on the main axis.
| Value | Effect |
|---|---|
| `start` | Places children at the beginning |
| `end` | Places children at the end |
| `center` | Groups children in the middle |
| `spaceBetween` | Puts equal space between children |
| `spaceAround` | Gives each child equal surrounding space |
| `spaceEvenly` | Gives every gap, including edges, equal space |
start and end refer to the beginning and end of the main axis. In a Row, text direction can affect which physical side those names represent.
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const Icon(Icons.star),
const Text('Rating'),
const Text('4.8'),
],
)This Row places the first child at the start, the last child at the end, and distributes the remaining space between them.
CrossAxisAlignment
The crossAxisAlignment property positions children across the main axis.
Common values include:
start: align children at the beginning of the cross axis.end: align children at the end.center: center each child.stretch: make children fill the available cross-axis space.baseline: align text by its typographic baseline.
For a Row, CrossAxisAlignment.start means the top edge. For a Column, it means the left or leading edge.
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('Title'),
const SizedBox(height: 8),
const Text('Subtitle'),
],
)The texts share the same leading edge. The SizedBox adds a fixed vertical gap.
baseline is useful when different text styles have different heights. A Row using it usually also needs a textBaseline property.
Common mistakes
MainAxisAlignment.spaceBetween has no visible effect when the Row or Column has no extra main-axis space. Give the parent a larger size, or use MainAxisSize.max, which is the default.
CrossAxisAlignment.stretch also needs a finite cross-axis constraint. For example, a Column can stretch children horizontally when its width is bounded.
Exercise
In a Column, which property centers children horizontally, and why?
Show answer
Use crossAxisAlignment: CrossAxisAlignment.center because a Column's cross axis is horizontal.