How does the Alignment property works in a Container widget in Flutter? I have the following code which does not have the alignment property in the container.
return GridTile(
child: Column(children: <Widget>[
Image.network(_workoutCategories[index].imageURL),
Container(
color: const Color(0xffe67e22),
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Text(_workoutCategories[index].name, style: TextStyle(color: Colors.white, fontSize: 24)),
),
)
]),
);
And here is the result:
When I add the alignment property on the Container, the Container seems to stretch to fill the parent as shown below:
I thought alignment property is just used to align the child widgets. What is going on?
topRight. This places the FlutterLogo in the top right corner of the parent blue Container. The Alignment used in the following example defines a single point: (0.2 * width of FlutterLogo/2 + width of FlutterLogo/2, 0.6 * height of FlutterLogo/2 + height of FlutterLogo/2) = (36.0, 48.0).
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.
Center Align Elements To horizontally center a block element (like <div>), use margin: auto; Setting the width of the element will prevent it from stretching out to the edges of its container.
First, you have to understand that the alignment
property doesn't refer to Container
alignment, but to its child's alignment.
Imagine that what defines the alignment of the child is the corner it is touching. If you align it to the left, the child will touch the left corner. However, a child cannot be properly aligned if the parent doesn't fill all the space available, since if the parent takes the minimum possible space, the child will touch all corners of the parent. That's why the Container
has to fill all the space when you set an alignment, otherwise the child won't be able to respect that alignment.
In your case, if you don't want the orange box to fill all the space and still in the center, then wrap it in another container with the center alignment:
Container(
alignment: Alignment.center,
Container(
color: const Color(0xffe67e22),
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Text(_workoutCategories[index].name, style: TextStyle(color: Colors.white, fontSize: 24)),
),
),
)
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