Reputation: 9660
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?
Upvotes: 17
Views: 105163
Reputation: 8427
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)),
),
),
)
Upvotes: 53