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:
- Flutter: Text with Read More / Read Less Buttons
- Flutter: Making a Tic Tac Toe Game from Scratch
- 2 Ways to Create Typewriter Effects in Flutter
- Flutter TextField: Styling labelText, hintText, and errorText
- Flutter: Adding a Clear Button to a TextField
- Flutter: Adding a Gradient Border to a Container (2 Examples)
You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.