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:
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:
Row(mainAxisAlignment: MainAxisAlignment.center)
Center vertically w/Column:
Column(mainAxisAlignment: MainAxisAlignment.center)
The alignment above is the desired result. Can those results be achieved with other Flutter widgets?
Using Stack's alignment property, you can align all the widgets in one direction. For example, all widgets in the center, all widgets in the bottom right, and so on. To position the widget in the Stack, simply add the alignment property and give it the alignment of your choice.
In Flutter, to vertically center a child widget inside a Container, you can wrap the child widget with Column and add mainAxisAlignment: MainAxisAlignment. center to it.
Flutter – Center Align Horizontally in Column To center align contents of Column widget horizontally, set crossAxisAlignment attribute with CrossAxisAlignment.
The solution is to place a Container as the only children in the ListView , and give it a minimum height equal to the available space for the height (Use LayoutBuilder to measure the maximum height for the widget). Then as the Container 's child, you can either place a Center or Column (with MainAxisAlignment.
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
2. For Center Left use alignment: Alignment.centerLeft
3. For Center right use alignment: Alignment.centerRight
3. For Bottom center use alignment: Alignment.bottomCenter
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With