Search code examples
flutterlayout

Flutter: If constraints go down and sizes go up, then why does Expanded exist?


I am trying to understand how the Flutter layout system works.

I read in the docs that, on Flutter, "constraints go down and sizes go up", meaning, the parent tells the child what its sizes contraints are, and the child tells the parent their chozen size.

And then I read the definition of the Expanded widget:

A widget that expands a child of a Row, Column, or Flex so that the child fills the available space.

Question: Doesn't Expanded break the above rule? My understanding is that a parent shouldn't tell its children its size, and that's what Expanded is doing. Also, without the Expanded, the children would already know its constraints and they could be 100% width and height if they wanted.

What am I getting wrong?


Solution

  • I am the author of that article in the docs.

    My understanding is that a parent shouldn't tell its children its size

    Not exactly. The parent tells its children the constraints, which are the min and max size each child can have. So the child cannot have any size it wants. It must be within those constraints.

    If the parent tells a child it can have a minimum of 80 pixels and a maximum of 80 pixels, then yes, the parent is in practice telling the child its size, as the only answer the child can give here is 80 pixels. This is called a "tight" constraint.

    That's exactly what the Expanded does. It tells the child it must have at min and at max the same size as the Expanded, so that the child can only "decide" to have the same size of the Expanded.

    By the way, if instead of the Expanded you use a Flexible widget, it will tell the child to have at max the same size as the Flexible, but the min will be set at 0. This is called a "loose" constraint.