45

I'm practicing with flutter Container these days, and this example I came up with is simply astonishing

I put a Container of size 50x50 inside a Container of size 200x200. Strange is that the inner Container expand to 200x200 even though it has a tight constraint of 50x50.

Here's the code

Container(
  width: 200.0,
  height: 200.0,
  color: Colors.orange,
  child: Container(
    width: 50.0,
    height: 50.0,
    color: Colors.blue,
  ),
)

I expect a small blue box inside a bigger orange box.

Could someone explain why?

2 Answers 2

110

You need to specify where in the orange box you would like the blue box displayed, otherwise the blue box will grow to the size of its parent.

  Container(
    width: 200.0,
    height: 200.0,
    color: Colors.orange,
    alignment: Alignment.center, // where to position the child
    child: Container(
      width: 50.0,
      height: 50.0,
      color: Colors.blue,
    ),
  ),
1
  • 8
    It's almost 3 years later. Having to still specify the alignment as shown to avoid the unexpected expansion of the inner container is still very non-intuitive. Couldn't have the Flutter team specified a default Alignment such as Alignment.topLeft to then avoid such illogic?! Commented Aug 3, 2021 at 6:47
0

In the code below we created a container that has a child called text and tried to style them a bit to make them look better.

Container(
  width: double.infinity,
  decoration: BoxDecoration(
    color: Colors.amber,
    borderRadius: BorderRadius.circular(15)
  ),
  padding: const EdgeInsets.all(10),
  margin: const EdgeInsets.all(10),
  child: const Text('orange juice is very delicious',
     textAlign: TextAlign.center,
     style: TextStyle(
       color: Colors.white,
       fontSize: 22,
       fontWeight: FontWeight.bold
     ),
  ),
),

Not the answer you're looking for? Browse other questions tagged or ask your own question.