Sub topic 3
Row and Column basics
This chapter assumes you can write a StatelessWidget with a build method, read Dart named parameters and lists, and run a Flutter app. It also assumes you know the rule from the previous chapter: constraints go down and sizes go up. Here you will use that rule to see what Row and Column do.
What Row and Column are
Row and Column are widgets that lay out a list of children in one direction. Row places children left to right. Column places them top to bottom. Both are thin subclasses of a single widget named Flex. The only difference is the direction (Axis.horizontal or Axis.vertical). Almost everything you learn about one applies to the other with the axes swapped.
Neither widget scrolls. Each lays out all its children in one line, and if they don't fit, you get an overflow error. The "When Row and Column are not enough" chapter later in this tutorial covers scrolling alternatives.
A minimal Row looks like this:
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: Scaffold(body: Demo())));
class Demo extends StatelessWidget {
const Demo({super.key});
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const Icon(Icons.star),
const Text('Rating'),
const Text('4.8'),
],
);
}
}The Row places the icon and the two texts left to right. It spreads the free horizontal space between them and centers them vertically. The children parameter is a List<Widget>, and the order of the list is the order on screen.
A Column has the same shape:
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('Title'),
const SizedBox(height: 8),
const Text('Subtitle'),
],
)The Column stacks the three children vertically and aligns them to the left edge. The SizedBox is an invisible 8-pixel gap.
How a Row negotiates its size
Layout in a Row follows the constraints-down, sizes-up rule in two passes. The following table describes a Row. For a Column, swap width and height.
| Step | Who acts | What happens |
|---|---|---|
| 1 | Parent | Gives the `Row` a min and max width and height. |
| 2 | Row | Lays out each non-flexible child with the same max height and an unbounded width. |
| 3 | Row | Divides the remaining width among flexible children (`Expanded`, `Flexible`). |
| 4 | Row | Picks its own width, then its height from the tallest child, within the parent's constraints. |
| 5 | Row | Positions each child using the alignment properties. |
Two consequences follow from this table.
First, a Row gives its children an unbounded width during step 2. A child that wants to be as wide as its content, such as a long Text, can therefore grow past the screen edge. That is the cause of the yellow-and-black overflow stripe.
Second, a Row is as wide as its parent allows by default, but only as tall as its tallest child. A Column is the mirror image: it is as tall as its parent allows, but only as wide as its widest child.
Replace nothing above; the diagram below is the one to use.
Default behavior
When you write Row(children: [...]) with no other arguments, you get these defaults:
| Property | Default | Effect |
|---|---|---|
| `mainAxisAlignment` | `MainAxisAlignment.start` | Children are packed at the left of a `Row` (top of a `Column`). |
| `crossAxisAlignment` | `CrossAxisAlignment.center` | Children are centered on the other axis. |
| `mainAxisSize` | `MainAxisSize.max` | The widget takes all the space on its main axis that the parent allows. |
The default center on the cross axis surprises many people. A Column of three Text widgets with no other settings centers each one horizontally within the column's width. The column's width is the width of its widest child, so the effect is invisible until another child makes it wider.
The next chapters cover the properties in detail. For now, remember that these three exist and what their defaults are.
Building a small layout
This example is a typical list-row building block: an icon, a two-line label, and a trailing value. It nests a Column inside a Row.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: Scaffold(body: Demo())));
class Demo extends StatelessWidget {
const Demo({super.key});
@override
Widget build(BuildContext context) {
return const SafeArea(
child: Padding(
padding: EdgeInsets.all(16),
child: Row(
children: [
Icon(Icons.wifi, size: 32),
SizedBox(width: 12),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Wi-Fi'),
SizedBox(height: 4),
Text('Connected'),
],
),
],
),
),
);
}
}Trace the layout using the table above. The Row receives a max width equal to the screen width, minus the 16-pixel padding on each side. It asks the Icon for a size (32 by 32) and the SizedBox for 12 by 0. It then asks the Column for a size with an unbounded width. The Column returns the width of its widest Text and a height that is the sum of its three children. The Row is as tall as the Column, the tallest child. The icon is centered vertically against it because the default cross axis alignment is center.
Notice the nesting direction. A Column inside a Row is normal and common. Real screens are built from many such nestings.
Rules that explain most errors
Layout errors with Row and Column almost always come from the same few rules.
- A child of a
Rowgets unbounded width. If it has no intrinsic width limit, such as a longText, it overflows. The fix is to give it a bounded width by wrapping it inExpanded. - A child of a
Columngets unbounded height. AListViewis the usual victim. It tries to be as tall as possible, finds no limit, and throws a "Vertical viewport was given unbounded height" error. - A
Rowdirectly inside aRow(or aColumndirectly inside aColumn) is a trap. The inner one receives an unbounded constraint on its main axis, so its own flexible children cannot be resolved. Expandedonly works as a direct child of aRow,Column, orFlex. Anywhere else, Flutter reports an "Incorrect use of ParentDataWidget" error.
For instance, this snippet fixes rule 1:
Row(
children: [
const Icon(Icons.info),
const SizedBox(width: 8),
Expanded(
child: Text(
'A very long message that would otherwise overflow the Row',
overflow: TextOverflow.ellipsis,
),
),
],
)The Expanded gives the Text the width left over after the icon and the gap. The text wraps or truncates inside that width instead of running off the screen. Text wraps onto a second line unless you set overflow and maxLines, so the ellipsis appears only when maxLines is set, or when the text can't wrap.
This snippet fixes rule 2:
Column(
children: [
const Text('Header'),
Expanded(
child: ListView(
children: const [
ListTile(title: Text('One')),
ListTile(title: Text('Two')),
ListTile(title: Text('Three')),
],
),
),
],
)Here the Expanded hands the ListView a fixed height: whatever remains after the header. Both fixes are expanded in the chapter on Expanded, Flexible, and overflow.
Practical habits
- Mark widgets
constwhere you can. Aconst Text('Rating')inside aRowis created once and reused, so rebuilds are cheaper. - Use
SizedBoxfor fixed gaps between children. It's clearer than padding on each child, and the "Adding space with SizedBox and Padding" chapter compares the two. - Read the constraint message. Flutter's errors name the widget, the constraint (for example
BoxConstraints(w=360.0, 0.0<=h<=Infinity)), and the nearest ancestor that caused it. TheInfinityshows you which axis is unbounded. - Avoid deep nesting in one
buildmethod. If aRowcontains aColumnthat contains anotherRow, extract the inner part into its own widget class.
Exercise
A Column contains a Text('Header') and then a ListView. The app throws "Vertical viewport was given unbounded height". Using the rule for how a Column lays out its children, explain why this happens and give the one-widget fix.
Show answer
A Column lays out its children with an unbounded maximum height, so each child may grow as tall as it likes. A ListView tries to fill all the height it is offered, and an unbounded height is infinite, so it has no valid size and Flutter throws the error. Wrap the ListView in Expanded. Expanded gives it the finite height that remains after the Text is laid out.
Exercise
You write Row(children: [Icon(Icons.info), Text('A very long sentence that does not fit on one line at all')]) on a narrow phone screen and see an overflow stripe. What constraint did the Text receive, and how do you make it wrap inside the available width?
Show answer
In a Row, each non-flexible child receives an unbounded maximum width, so the Text laid itself out on one line at its natural width, which is wider than the screen. Wrap the Text in Expanded. The Row then gives it only the width left after the icon, and the text wraps within that width.