Flutter - Using Spacer Widget Examples

This is a tutorial of how to use Spacer widget in Flutter.

Flutter has a widget called Spacer. It's used to create spacing between widgets. The most common usage for Spacer is for creating adjustable spaces between widgets in a Flex container, such as Row or Column. Though Flutter provides some predefined alignments like spaceBetween, spaceAround, and spaceEvenly, sometimes we may need to set custom spacing. That's why the Spacer widget can be useful.

Using Spacer

It has a simple constructor. There is no required argument.

  const Spacer({Key key, this.flex = 1})

Below is the description of the arguments you can pass on the constructor.

  • Key key: The widget key, used to control if it should be replaced.
  • int flex: The flex factor used to determine the size of the space. Defaults to 1.

Let's start with a basic usage of the widget. You need to put it on each place where you want a space to exist. Flutter will automatically calculate the size of each space, so that all spaces have the same size.

  SizedBox(
    height: 50,
    child: Row(
      children: <Widget>[
        Container(
          width: 50,
          color: Colors.red,
        ),
        Spacer(),
        Container(
          width: 50,
          color: Colors.green,
        ),
        Spacer(),
        Container(
          width: 50,
          color: Colors.blue,
        ),
        Container(
          width: 50,
          color: Colors.yellow,
        ),
      ],
    ),
  )

Output:

Flutter - Spacer - Basic 

 

Using Spacer with flex

What if you want the spaces to have different sizes. You can use flex property whose default value is 1. If a Spacer has a flex size of 3, it will be three times bigger than a Spacer with a flex size of 1.

In the below example, the first Spacer has a flex value of 3, while the second's is 1 and the third's is also 1. In total, 3 + 1 + 1 = 5. Therefore, 3/5 of the space is applied to the first one, while the second and third each get 1/5.

  SizedBox(
    height: 50,
    child: Row(
      children: <Widget>[
        Container(
          width: 50,
          color: Colors.red,
        ),
        Spacer(flex: 3),
        Container(
          width: 50,
          color: Colors.green,
        ),
        Spacer(flex: 1),
        Container(
          width: 50,
          color: Colors.blue,
        ),
        Spacer(),
        Container(
          width: 50,
          color: Colors.yellow,
        ),
      ],
    ),
  )

Output:

Flutter - Spacer - Flex

 

The size of the spaces by using Spacer widget depends on the available space. If you need to create spaces with fixed size, you can consider to use SizedBox.