gfit21x
gfit21x

Reputation: 151

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)

Upvotes: 4

Views: 707

Answers (1)

CoderUni
CoderUni

Reputation: 6164

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:

  Container({
    Key? key,
    this.alignment,
    this.padding,
    this.color,
    this.decoration,
    this.foregroundDecoration,
    double? width,
    double? height,
    BoxConstraints? constraints,
    this.margin,
    this.transform,
    this.transformAlignment,
    this.child,
    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!;

Upvotes: 5

Related Questions