Sub topic 4
Main axis and cross axis
This chapter assumes you can read basic Dart, have written a StatelessWidget, and know that a parent passes constraints down and a child reports a size back (the previous chapters covered both). It also assumes you have seen Row and Column used in simple cases. Here you will learn the two-axis model that every Row and Column uses, and how to predict which axis a given size or constraint applies to.
Two axes, one widget
Row and Column are both thin subclasses of a single widget, Flex. A Flex lays children out along one line. It has a main axis, which is the direction of that line, and a cross axis, which is perpendicular to it. The only thing that differs between the two widgets is which direction is the main one.
| Property | `Row` | `Column` |
|---|---|---|
| Main axis | Horizontal | Vertical |
| Cross axis | Vertical | Horizontal |
| Main axis starts at | Left (in left-to-right text) | Top |
| Cross axis starts at | Top | Left (in left-to-right text) |
| Main size by default | As wide as the incoming max width | As tall as the incoming max height |
| Cross size | Height of the tallest child | Width of the widest child |
Once you think in "main" and "cross" instead of "horizontal" and "vertical", every property on these widgets reads the same way for both. For example, MainAxisAlignment.end pushes children right in a Row and down in a Column. The alignment properties get their own chapter. This chapter explains the model they rely on.
How each axis is sized
The two axes are treated differently during layout. The Flex receives constraints from its parent, then gives each child its own constraints, then picks its own size from the results.
For the cross axis:
- Each child gets a minimum of 0 and a maximum equal to the
Flex's own cross-axis maximum. The exception isCrossAxisAlignment.stretch, which makes the minimum equal to the maximum, so every child is forced to fill the cross axis. - The
Flex's cross size is the largest child cross size, clamped to the incoming constraints.
For the main axis:
- Children without a flex factor (a plain
Text,Icon, orContainer) are measured first, with an unbounded main-axis maximum. They choose any size they like along the main axis. - The leftover space is then shared among
ExpandedandFlexiblechildren. That is the topic of a later chapter. - The
Flex's main size depends onmainAxisSize. WithMainAxisSize.max(the default) it takes the largest size the parent allows. WithMainAxisSize.minit shrinks to the sum of its children.
The asymmetry matters. A child can be as large as it wants along the main axis and is only limited across the cross axis. This is why a long Text in a Row overflows to the right instead of wrapping, while a long Text in a Column wraps at the column's width.
A runnable example
This app draws three boxes of different heights in a Row, and the same three boxes in a Column. Each is inside a bordered, fixed-size parent so you can see where the axes end.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: AxesDemo()));
class Box extends StatelessWidget {
const Box(this.color, this.width, this.height, {super.key});
final Color color;
final double width;
final double height;
@override
Widget build(BuildContext context) =>
Container(width: width, height: height, color: color);
}
class Frame extends StatelessWidget {
const Frame({super.key, required this.child});
final Widget child;
@override
Widget build(BuildContext context) => Container(
width: 200,
height: 200,
decoration: BoxDecoration(border: Border.all()),
child: child,
);
}
class AxesDemo extends StatelessWidget {
const AxesDemo({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Center(
child: Wrap(
spacing: 16,
runSpacing: 16,
children: [
Frame(
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: const [
Box(Colors.red, 40, 40),
Box(Colors.green, 40, 80),
Box(Colors.blue, 40, 120),
],
),
),
Frame(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: const [
Box(Colors.red, 40, 40),
Box(Colors.green, 80, 40),
Box(Colors.blue, 120, 40),
],
),
),
],
),
),
),
);
}
}In the Row, the boxes sit side by side from the left edge, because left is the start of the main axis. They are centered vertically, because the cross axis is vertical and the alignment is center. In the Column, the same code produces boxes stacked from the top and centered horizontally. Only the main axis changed.
Start does not always mean left
"Start" on the main axis is not a fixed screen side. Flutter ties it to two direction settings:
textDirectiondecides where the horizontal axis starts. It isltrby default for left-to-right languages, andrtlfor languages like Arabic and Hebrew. It affects the main axis of aRowand the cross axis of aColumn.verticalDirectiondecides where the vertical axis starts. It isVerticalDirection.downby default. It affects the main axis of aColumnand the cross axis of aRow.
If you read the ambient Directionality (provided by MaterialApp from the locale), a Row flips automatically in right-to-left locales. You can also force it for one subtree:
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: DirectionDemo()));
class DirectionDemo extends StatelessWidget {
const DirectionDemo({super.key});
@override
Widget build(BuildContext context) {
return const Scaffold(
body: Center(
child: Directionality(
textDirection: TextDirection.rtl,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text('First'),
SizedBox(width: 12),
Text('Second'),
],
),
),
),
);
}
}Here "First" appears on the right and "Second" on the left. The widget order in the list did not change. Only the direction of the main axis did.
Setting verticalDirection: VerticalDirection.up on a Column makes it build from the bottom upward, and the first child ends up at the bottom. On a Row it moves the cross-axis start to the bottom, so CrossAxisAlignment.start aligns children to the bottom edge. This surprises people who assume start always means top.
Nesting flips the axes
Each Flex has its own axes, independent of its parent. A Row inside a Column has a horizontal main axis, even though its parent's main axis is vertical. What the parent passes down, though, follows the parent's axes:
- A
Columngives its childRowa maximum width (the column's cross axis) and an unbounded maximum height (the column's main axis). - The
Rowuses the width as its main-axis limit, and its own height becomes the height of its tallest child.
This is the source of most "which axis is bounded?" confusion. A useful habit is to ask, for any widget in a Flex: what is the constraint on the parent's main axis, and what is the constraint on its cross axis? The answers are almost always "unbounded" and "bounded by the parent's size".
Stretch and the unbounded axis
CrossAxisAlignment.stretch asks every child to fill the cross axis. It needs a bounded cross axis to do that.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: StretchDemo()));
class StretchDemo extends StatelessWidget {
const StretchDemo({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: SizedBox(
height: 120,
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Container(width: 60, color: Colors.orange),
Container(width: 60, color: Colors.teal),
],
),
),
);
}
}The SizedBox supplies a height of exactly 120, so both containers stretch to 120 even though neither sets a height. Remove the SizedBox and put the same Row directly in a Column or ListView, and the vertical constraint becomes unbounded. Flutter then cannot stretch to "infinity" and throws a layout error about infinite height. The fix is to give the Row a bounded height, or to wrap it in IntrinsicHeight, which measures the children first. IntrinsicHeight has a cost, because it triggers an extra layout pass, so use it sparingly.
Common mistakes
- Expecting
crossAxisAlignmentto change the main axis. Cross-axis alignment never moves children along the main axis. UsemainAxisAlignmentfor that. - Centering a
ColumnwithmainAxisAlignmentand seeing no effect. TheColumnmust have spare vertical space. WithMainAxisSize.minthere is none, so nothing moves. - Expecting a
Columnto be as wide as the screen. AColumn's cross size is its widest child. Wrap it inSizedBox(width: double.infinity)or usecrossAxisAlignment: CrossAxisAlignment.stretchinside a bounded parent if you want full width. - Assuming
startis the top-left. It depends ontextDirectionandverticalDirection.
Exercise
A Row sits directly inside a Column inside a Scaffold body. You set crossAxisAlignment to CrossAxisAlignment.stretch on the Row, and its children have no explicit height. What goes wrong, and name two ways to fix it.
Show answer
The Row's cross axis is vertical, and the Column passes down an unbounded maximum height because height is the Column's main axis. Stretch tries to force every child to that infinite height, so layout fails with an error about infinite height. Fix it by giving the Row a bounded height (for example, wrap it in a SizedBox with a height), or by wrapping the Row in IntrinsicHeight so the tallest child sets the height. Giving the children explicit heights and dropping stretch also works.
Exercise
In a Column with verticalDirection set to VerticalDirection.up, which edge does the first child touch when mainAxisAlignment is MainAxisAlignment.start, and how does that differ from the default?
Show answer
The first child touches the bottom edge, because start is where the main axis begins and verticalDirection up makes the vertical axis begin at the bottom. By default (VerticalDirection.down) the first child touches the top edge.
Exercise
A Column has three Text children and no other settings. The widest Text is 180 logical pixels wide, and the Column is placed in a parent that allows widths up to 400. How wide is the Column, and which property would you set to make it 400 wide?
Show answer
With the default MainAxisSize.max applying only to the main (vertical) axis, the Column's width is the widest child, 180. To make it 400 wide, set crossAxisAlignment to CrossAxisAlignment.stretch (the parent gives a bounded 400 maximum), or wrap the Column in a SizedBox with width: double.infinity.