Flutter: Constraints not constraining widget (explanation needed)

Viewed 6369
class Test extends StatelessWidget {
  Widget build(BuildContext context) {
    return UnconstrainedBox(
        child: Container(
            height: 250.0,
            width: 250.0,
            decoration:
                BoxDecoration(shape: BoxShape.circle, color: Colors.red),
            child: Opacity(
                opacity: 0.5,
                child: Container( // WIDGET IN QUESTION
                    constraints:
                        BoxConstraints.expand(width: 50.0, height: 50.0),
                    color: Colors.yellow))));
  }
}

According to the Container class documentation...

If the widget has no child and no alignment, but a height, width, or constraints are provided, then the Container tries to be as small as possible given the combination of those constraints and the parent's constraints.

Instead, the widget is trying to be as large as possible (size of parent) rather than 50x50. I understand that I can use something like UnconstrainedBox, but I'm looking for an explanation of this behavior.

Looking for: looking-for

Currently getting: currently-getting

1 Answers

The problem is your root Container.

By setting a width+height without an alignment, Container forces its child to fill the available space.

If you want that child take the least amount of space, you need to specify your root container how it should align its child within its bounds.

Container(
  width: 250,
  height: 250,
  alignment: Alignment.center,
  child: Whatever(),
);
Related