Sometimes, dealing with box constraints in Flutter can be confusing and unclear. In this shot, we will discuss what they are and how to use them.
Let’s get started!
A constraint
is a set of 4 doubles:
maxHeight
)minHeight
)maxWidth
)minWidth
)The Flutter layout is an absolute foundation.
As stated in the official documentation:
Constraints go down. Sizes go up. The parent sets the position.
But what does that mean?
constraint
from its parent.constraints
are and asks them for their size.We can use BoxConstraints
in a few different ways.
constraints: BoxConstraints(
maxHeight: 300.0,
maxWidth: 300.0,
minHeight: 200.0,
minWidth: 200.0,
),
Here, we can manually set all the constraints
.
expand
property:constraints: BoxConstraints.expand(),
This will expand the widget in every direction (x and y-axis) to the constraints of its parent.
We can also pass height
:
constraints: BoxConstraints.expand(height: 100),
and width
:
constraints: BoxConstraints.expand(width: 100),
so that the constraints
will require exactly the given value in the given dimension.
loose
property:constraints: BoxConstraints.loose(
Size(200.0, 100.0)
),
This will create box constraints
that forbid sizes larger than the given size.
This is equivalent to just
setting the maximum height
and width
:
constraints: BoxConstraints(
maxHeight: 200.0,
maxWidth: 100.0,
),
tight
property:constraints: BoxConstraints.tight(
Size(200, 100)
),
which sets
maxHeight = minHeight = size.height
maxWidth = minWidth = size.width
In our case, the equivalent would look something like this:
constraints: BoxConstraints(
maxHeight: 200.0,
maxWidth: 200.0,
minHeight: 100.0,
minWidth: 100.0,
),
tightFor
property:constraints: BoxConstraints.tightFor(),
which accepts height
and width
arguments and sets:
minWidth = width ?? 0.0,
maxWidth = width ?? double.infinity,
minHeight = height ?? 0.0,
maxHeight = height ?? double.infinity;
tightForFinite
property:constraints: BoxConstraints.tightForFinite(),
which accepts height
and width
arguments (like tightFor
), but they are set to double.infinity
as a default.
minWidth = width != double.infinity ? width : 0.0,
maxWidth = width != double.infinity ? width : double.infinity,
minHeight = height != double.infinity ? height : 0.0,
maxHeight = height != double.infinity ? height : double.infinity;
There is a widget made specifically for setting BoxConstraints
called ConstrainedBox
. It accepts the constraints
argument and looks like this:
child: ConstrainedBox(
constraints: BoxConstraints(),
child: Container(),
),
As you can see, dealing with BoxConstraints
in Flutter can be complicated. I hope that, after reading this shot, you understand the basic concept of it.
If you want to know more about this topic, please read “Understanding constraints” from the official Flutter documentation.