okaryo.log

How to Center the Middle Element in a Row with 3 Elements in Flutter | okaryo.log

How to Center the Middle Element in a Row with 3 Elements in Flutter

    #Flutter

Introduction

When developing with Flutter, there are times when you want to center the middle element in a Row with three elements. While Row has a property called mainAxisAlignment for alignment, it might not work as expected to center the middle element when the element sizes differ.

Consider the following Row where each element has a different size.

Row(
  mainAxisAlignment: MainAxisAlignment.xxx,
  children: [
    Container(
      width: 80,
      height: 50,
      color: Colors.blue,
    ),
    Container(
      width: 50,
      height: 50,
      color: Colors.red,
    ),
    Container(
      width: 120,
      height: 50,
      color: Colors.green,
    ),
  ],
),

When setting the mainAxisAlignment to spaceAround, spaceBetween, or spaceEvenly, the middle element will be shifted to the left because the element sizes vary.

SpaceAround SpaceBetween SpaceEvenly

This UI layout might be occasionally needed, so I will keep it here.

Solution

To solve this issue, you can wrap the left and right elements with Expanded, which will push the middle element to the center. You can use Align to position the elements inside Expanded as you like. By the way, the default value of Align’s alignment property is Alignment.center.

Row(
  children: [
    Expanded(
      child: Align(
        child: Container(
          width: 80,
          height: 50,
          color: Colors.blue,
        ),
      ),
    ),
    Container(
      width: 50,
      height: 50,
      color: Colors.red,
    ),
    Expanded(
      child: Align(
        alignment: Alignment.centerRight,
        child: Container(
          width: 120,
          height: 50,
          color: Colors.green,
        ),
      ),
    ),
  ],
),

Applying this will result in the middle element being centered on the screen, as shown below.

ExpandedAndAlign

If you want to push the left and right elements to the sides without using Align, you can achieve this with Expanded and Spacer as shown below.

Row(
  children: [
    Expanded(
      child: Container(
        width: 80,
        height: 50,
        color: Colors.blue,
      ),
    ),
    const Spacer(),
    Container(
      width: 50,
      height: 50,
      color: Colors.red,
    ),
    const Spacer(),
    Expanded(
      child: Container(
        width: 120,
        height: 50,
        color: Colors.green,
      ),
    ),
  ],
),

ExpandedAndSpacer

This approach simplifies the code by removing Align.

Conclusion

There are still many Widgets and properties in Flutter that I don’t know about, so there might be an even smarter and simpler way to do this. If you know of one, please feel free to share it in the comments!


Related Posts
Related Posts
Promotion

This site uses Google Analytics.