Rafael Delos Santos · Software engineer


Axis alignment of Columns and Rows in Flutter

There are different ways to align widgets within a Column and a Row. Both widgets share similar properties, yet each differs based on their axes. In this tutorial, we will see the effects of applying different types of alignments to both Column and Row.

Column and Row refresher

A Column widget arranges its child widgets vertically, therefore defining its main axis as the Y-Axis. A Row on the other hand does it horizontally, which means that its main axis is the X-Axis. It is important to keep this in mind so we know which properties we should change to achieve a certain result.

Arranging the child widgets using mainAxisAlignment

The mainAxisAlignment modifies how the widgets are arranged vertically in a Column and horizontally in a Row. Changing this property affects either the position of the widgets along the main axis or the spacing between the child widgets.

Column(
  mainAxisAlignment: MainAxisAlignment.start, //<< Change this
  children :[...]
);

Row(
  mainAxisAlignment: MainAxisAlignment.start, //<< Change this
  children :[...]
);

Look at the following illustrations to learn how each type of main axis alignment affects a Column.

column-main-axis-alignment

And now for a Row, changing the mainAxisAlignment arranges the child widgets like in the image below.

row-main-axis-alignment

For reference, the mainAxisAlignment properties are:

What about crossAxisAlignment?

The crossAxisAlignment property arranges the widget opposite of the main axis called the cross axis.

Column(
  crossAxisAlignment: CrossAxisAlignment.start, //<< Change this
  children :[...]
);

Row(
  crossAxisAlignment: CrossAxisAlignment.start, //<< Change this
  children :[...]
);

Have a look at the different crossAxisAlignment values and how child widgets would look inside a Column.

column-cross-axis-alignment

For crossAxisAlignment in a Row, the child widget arrangement will be along the vertical axis.

row-cross-axis-alignment

For reference, here are the crossAxisAlignment values:

Using the CrossAxisAlignment.stretch would throw a BoxConstraints error if the parent widget of the Row or Column does not have a constrained width e.g. parent widgets are Row or Column as well.

Summary

The mainAxisAlignment and crossAxisAlignment are the main properties to arrange the child widgets of Columns and Rows. Just remember that Column has a vertical main axis and Row has a horizontal main axis. The layouts' cross axes will be the opposite of their main axes.


References