Search code examples
flutterflutter-layout

Flutter Container's BoxConstrains not working as expected


this is the code

return MaterialApp(
  home: Container(
    constraints: BoxConstraints.tight(Size(100, 100)),
    decoration: BoxDecoration(color: Colors.yellow),
    child: Card(child: Text('Hello World')),
  ),
);

what i expected is Card is 100 x 100, but it's not, it just stretched to the whole screen. why does it happened?

container not working as i expected


Solution

  • The Flutter team released a great article named "Understanding constraints" that's definitely worth checking out if you're unsure about how constraints work. That being said, here's a more in-depth answer specifically about your problem:

    Why do your BoxConstraints get ignored?

    The Container internally creates a ConstrainedBox in order to enforce your constraints. The ConstrainedBox's RenderObject - a RenderConstrainedBox - then tries to adhere to your constraints as much as possible.

    During layout, the following code taken from the RenderConstrainedBox implementation is executed. The members minWidth, maxWidth, minHeight and maxHeight stem from your given constraints, while constraints are the constraints provided by the Flutter framework (in your case, the screen size).

    BoxConstraints(
      minWidth: minWidth.clamp(constraints.minWidth, constraints.maxWidth),
      maxWidth: maxWidth.clamp(constraints.minWidth, constraints.maxWidth),
      minHeight: minHeight.clamp(constraints.minHeight, constraints.maxHeight),
      maxHeight: maxHeight.clamp(constraints.minHeight, constraints.maxHeight)
    )
    

    Because the screen size is inflexible, the constraints are tight, meaning constraints.minWidth == constraints.maxWidth and constraints.minHeight == constraints.maxHeight. That forces clamp to ignore your constraints (for example, 2.clamp(3,3) == 3).

    So there you have it: The constraints you give to a Container will only be respected as much as possible. Because the whole screen needs to be filled, the Container is forced to take the tight screen constraints, thereby ignoring your constraints.

    What to do about it

    To make it possible for the Container to respect your constraints, you have to give it more "breathing room", i.e. don't force it to fill the screen. A simple solution would be to wrap it in a Center, but it depends on your preferences on where the Container should be aligned.