9.4 C
New York
Saturday, December 2, 2023

Flutter: Sizing a Container inside another Container

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

AdvertisementsThat’s it. Further reading:

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

Advertisements

Related Articles

Latest Articles