Ray Li
Ray Li

Reputation: 7919

How to vertically or horizontally center a Widget in a Stack?

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:

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?

Upvotes: 11

Views: 8363

Answers (1)

Jitesh Mohite
Jitesh Mohite

Reputation: 34270

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

Upvotes: 16

Related Questions