Flutter align two items on extremes – one on the left and one on the right

In Flutter, when you need to align two items on the extremes of a Row or Column widget, there are several approaches you can take. Here, we’ll explore some common methods used to achieve this layout.

Using MainAxisAlignment: spaceBetween

One simple and straightforward way to align two items at the extremes is by using a single Row with its mainAxisAlignment set to MainAxisAlignment.spaceBetween. This approach works for both horizontal and vertical layouts.

new Row(
  mainAxisAlignment: MainAxisAlignment.spaceBetween,
  children: [
    new Text("left"),
    new Text("right")
  ]
);

This code snippet creates a Row widget that contains two Text widgets labeled “left” and “right”. By setting the mainAxisAlignment to spaceBetween, Flutter will automatically align these items on opposite sides of the row.

Using Expanded Widget

Another approach is to use an Expanded widget within the Row. The Expanded widget allows you to specify how much space a child should occupy in the parent widget’s main axis (width for horizontal layouts and height for vertical layouts).

new Row(
  children: [
    new Text("left"),
    new Expanded(
      child: settingsRow,
    ),
  ],
);

In this example, we’re using a Row to display two items. The first item is simply a Text widget with the label “left”. For the second item, we’ve wrapped our actual content (let’s call it settingsRow) in an Expanded widget. This tells Flutter that settingsRow should expand to fill any remaining space after accounting for its parent’s width.

Since Expanded expands along the main axis of its parent, using it ensures that settingsRow occupies a significant portion of the row and pushes “left” towards the start (or left edge in case of horizontal layout).

A Simple Solution: Using Spacer()

A straightforward solution when you want to align two items at extremes is to place a Spacer() between them. A Spacer takes up space along its main axis without taking any visual or layout space.

Row(
  children: [
    Text("left"),
    Spacer(),
    Text("right")
  ]
);

In this example, we’re placing a Spacer widget after the first Text (“left”) and before the second Text (“right”). The Spacer will take up any available horizontal space in its parent (the Row) between these two widgets. This effectively aligns them on opposite sides of their parent.

Conclusion

In this guide, we’ve looked at three common methods for aligning items on the extremes within a Row or Column widget in Flutter: using MainAxisAlignment: spaceBetween, leveraging Expanded widget to occupy available space, and employing Spacer() to manage horizontal or vertical spacing. Each method has its use cases and can be applied based on the specific layout needs of your application.