4
votes

The Center widget centers a widget horizontally and vertically in the center of a Stack. How can one center a widget ONLY horizontally or vertically?

Centering a widget in a Stack is possible with a Row or Column widget. Can it be done without using those widgets?

Conditions:

  • Cannot use Row / Column.
  • The size of the Stack is not known before layout (cannot use hardcoded Positioned values).

Center widget:

Centered Widget in Stack

Container(
      decoration:
          BoxDecoration(border: Border.all(color: Colors.black87, width: 10)),
      child: Stack(
        children: [
          Center(
            child: Container(color: Colors.amber, width: 50, height: 50),
          ),
        ],
      ),
    );

Center horizontally w/Row:

Horizontally centered widget in Stack

Row(mainAxisAlignment: MainAxisAlignment.center)

Center vertically w/Column:

Vertically centered Widget in Stack

Column(mainAxisAlignment: MainAxisAlignment.center)

The alignment above is the desired result. Can those results be achieved with other Flutter widgets?

1

1 Answers

5
votes

Use Align Widget

 Align(
        alignment: Alignment.topCenter, // This will horizontally center from the top
        child: Container(
          decoration: BoxDecoration(
              border: Border.all(color: Colors.black87, width: 10)),
          child: Stack(
            children: [
              Container(color: Colors.amber, width: 50, height: 50),
            ],
          ),
        ),
      )

1. For Top Center use alignment: Alignment.topCenter

enter image description here

2. For Center Left use alignment: Alignment.centerLeft

enter image description here

3. For Center right use alignment: Alignment.centerRight

enter image description here

3. For Bottom center use alignment: Alignment.bottomCenter

enter image description here