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

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.

Tags:

Dart

Flutter