Flutter: Sizing a Container inside another Container

Updated: February 10, 2023 By: Augustus Post a comment

To size a Container that resides inside another Container, you need to set the alignment property of the parent Container to an alignment value. 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.

Scaffold(
      appBar: AppBar(title: const Text('Kindacode.com')),
      body: 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:

Scaffold(
      appBar: AppBar(title: const Text('Kindacode.com')),
      body: 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