When should you use mainAxisAlignment and crossAxisAlignment?
#flutter#widget#layout
Answer
Overview
text
mainAxisAlignmenttext
crossAxisAlignmenttext
Rowtext
ColumnAxis Directions
| Widget | Main Axis | Cross Axis |
|---|---|---|
text | Vertical (↕) | Horizontal (↔) |
text | Horizontal (↔) | Vertical (↕) |
mainAxisAlignment — Along the Main Axis
Controls spacing/positioning of children along the primary direction.
dartColumn( mainAxisAlignment: MainAxisAlignment.center, // children grouped at center vertically children: [Text('A'), Text('B'), Text('C')], )
| Value | Effect |
|---|---|
text | Pack children at the start (default) |
text | Pack children at the end |
text | Pack children at the center |
text | Equal space between children, no edge space |
text | Equal space around children (half at edges) |
text | Equal space between and at edges |
dartRow( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Icon(Icons.home), Icon(Icons.search), Icon(Icons.person), ], ) // Result: [HOME] [SEARCH] [PERSON]
crossAxisAlignment — Along the Cross Axis
Controls how children are aligned perpendicular to the main axis.
dartRow( crossAxisAlignment: CrossAxisAlignment.center, // children centered vertically children: [ Text('Hello', style: TextStyle(fontSize: 24)), Text('World', style: TextStyle(fontSize: 12)), ], )
| Value | Effect |
|---|---|
text | Align to the start of the cross axis |
text | Align to the end of the cross axis |
text | Center on the cross axis (default) |
text | Stretch children to fill the cross axis |
text | Align text baselines (use with text |
Common Examples
dart// Centered content in a Column Column( mainAxisAlignment: MainAxisAlignment.center, // Vertical center crossAxisAlignment: CrossAxisAlignment.center, // Horizontal center children: [ Icon(Icons.star, size: 48), Text('You're a star!'), ], ) // Bottom bar layout Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, // Spread icons evenly crossAxisAlignment: CrossAxisAlignment.center, // Vertically centered children: [ IconButton(icon: Icon(Icons.home), onPressed: () {}), IconButton(icon: Icon(Icons.search), onPressed: () {}), IconButton(icon: Icon(Icons.settings), onPressed: () {}), ], )
When to Use What
| Goal | Use |
|---|---|
| Center all content | text text |
| Space out nav bar items | text text |
| Stretch children to full width (in Column) | text |
| Left-align text in a Column | text |
| Push items to bottom of Column | text |
Memory Tip:
= the direction the widget flows.textmain= the other direction.textcross