Flutter: Space Control with mainAxisSize
Flutter mainAxisSize - Space Control
mainAxisSize determines how much space Row or Column widgets will take along the main axis. It draws an invisible boundary and prevents the widget from expanding infinitely.
What is mainAxisSize?
When you create a Row or Column, by default it tries to take up all available space. You can change this behavior with mainAxisSize.
Live Demo: mainAxisSize Examples
See the difference between mainAxisSize.max and mainAxisSize.min:
mainAxisSize Values
MainAxisSize.max (Default)
Row or Column takes up all available space along the main axis:
Row(
mainAxisSize: MainAxisSize.max, // Default
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.star),
Text('Maximum width'),
Icon(Icons.star),
],
)In this case, Row uses all available width horizontally.
MainAxisSize.min
Row or Column only takes up as much space as its children need:
Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.star),
Text('Minimum width'),
Icon(Icons.star),
],
)In this case, Row only takes up as much space as the total of the widgets inside.
Usage with Column
In Column, mainAxisSize works on the vertical axis:
Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('First line'),
Text('Second line'),
ElevatedButton(
onPressed: () {},
child: Text('Button'),
),
],
)When MainAxisSize.min is used, Column only takes up as much vertical space as the content.
MainAxisSize.max vs MainAxisSize.min
| Feature | MainAxisSize.max | MainAxisSize.min |
|---|---|---|
| Space usage | All available space | Only necessary space |
| Default | Yes | No |
| mainAxisAlignment effect | Distributes across full width | Only within content width |
| Use case | Where full width is desired | Compact layouts, dialogs |
When to Use?
Use MainAxisSize.max:
- When you want full width/height
- When you want to spread items across a wide area
- When default behavior is sufficient
Use MainAxisSize.min:
- In dialog contents
- In card and postcard layouts
- In button groups
- Where you want tight wrapping to content
- When you want to prevent unnecessary spaces
Summary
mainAxisSize is an important property that controls the space usage of Row and Column:
- max: Use all available space (default)
- min: Use only as much space as needed
By using this property correctly, you can create more compact and professional-looking layouts.