Flutter: Sizing a Container inside another Container

Last updated on February 11, 2022 Augustus Loading... Post a comment

To size a Container that resides inside another Container, you need to set the alignment property of the parent Container. Otherwise, the child Container won’t care about the width and height you set for it and will expand to its parent’s constraints.

Example

This example creates a 200 x 200 Container with a purple background color. Its parent is a bigger Container with an amber background.

Container(
        width: double.infinity,
        height: 400,
        color: Colors.amber,
        alignment: Alignment.bottomCenter,
        child: Container(
          width: 200,
          height: 200,
          color: Colors.purple,
        ),
),

Screenshot:

You can also wrap the child Container with a Center or an Align widget instead of setting the alignment property of the parent Container to Alignment.something, like so:

Container(
        width: double.infinity,
        height: 400,
        color: Colors.amber,
        child: Align(
          child: Container(
            width: 200,
            height: 200,
            color: Colors.purple,
          ),
        ),
),

That’s it. Further reading:

You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles