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:

enter image description here

When I add the alignment property on the Container, the Container seems to stretch to fill the parent as shown below: enter image description here

I thought alignment property is just used to align the child widgets. What is going on?


Solution 1: Hugo Passos

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)),
    ),
  ),
)


Solution 2: Mostafa Mohamed

what's the type of key's of align and how use it ?

Align( key: , alignment: Alignment.center, child: FloatingActionButton.extended( onPressed: () { Navigator.pushNamed(context, ListScreen.screenRoute); }, label: const Text( "Go", style: TextStyle( fontWeight: FontWeight.bold, fontSize: 20.0, ), ), icon: const Icon(Icons.book_outlined), backgroundColor: Colors.lightBlueAccent, ), ),