Giving a fixed width and height to a container vs providing constraints via a BoxConstraints class


In the Container widget in flutter,

What is the difference between giving it a fixed height and width AND providing it BoxConstraints for the constraints property?.

Is it either providing a width + height or constraints? Can they be both provided at the same time? What is the difference?

I also looked at the official docs which refers to the Container widget and in there, right under the heading called Layout Behavior they mention what happens when different combinations of width and height and constraints do? (But I do not understand how they differ)


TLDR: They do the same thing

Long Answer:
If you take a look at the Container‘s code you could see that the width and height you’ve provided actually gets turned into a BoxConstraints. Container will use that BoxConstraints to set its constraints. Here’s a October 2021 snippet of the Container‘s constructor:

    Key? key,
    double? width,
    double? height,
    BoxConstraints? constraints,
    this.clipBehavior = Clip.none,
  }) : // *Removed the asserts it made to make this snippet shorter
       // Important part is here
       constraints =
        (width != null || height != null)
          ? constraints?.tighten(width: width, height: height)
            ?? BoxConstraints.tightFor(width: width, height: height)
          : constraints,
       super(key: key);

Here is a portion of the Container‘s build method:

// Parts of the code removed to shorten snippet
if (constraints != null)
  current = ConstrainedBox(constraints: constraints!, child: current);
// Parts of the code removed to shorten snippet
return current!;

Answered By – Uni

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *