Flutter – Why Flutter Container does not respects its width and height constraints when it is inside other Container

dartflutter

Container(
  width: 200.0,
  height: 200.0,
  child: Container(
    width: 50.0,
    height: 50.0,
    decoration: BoxDecoration(
      shape: BoxShape.circle,
      color: Colors.red
    ),
  ),
)

I've been trying to find the answer in the Container class docs but I did not find it.

Update:

After a long time, I understood the problem.

All views inside a layout must have width, height, x position, and y position. (This applies to Android, IOS, Flutter, etc)

In my code, the inner container just has a width and height for that reason it doesn't know where to start painting.

For that reason, if the container is placed inside an Alignment widget the container gets the x position and y position and it works.

Best Answer

Constraints in Flutter works a bit different than usual. Widgets themselves do not have constraints.

When you specify a width/height on a Container, you're not constraining Container. You're constraining the child of Container.

Container will then size itself based on the size of its child.

As such, parent widgets always have the last word on how their descendants should be sized.

If you want to go around this, you have to use Align widget:

Container(
  width: 200.0,
  height: 200.0,
  child: Align(
    alignment: Alignment.topLeft,
    child: Container(
      width: 50.0,
      height: 50.0,
      decoration:
          BoxDecoration(shape: BoxShape.circle, color: Colors.red),
    ),
  ),
);

This may seem weird and limiting. But this single weirdness is the reason why Flutter's layout is so powerful and composable.

Related Topic