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!
constraint is a set of 4 doubles:
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?
constraintfrom its parent.
constraintsare 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
This will expand the widget in every direction (x and y-axis) to the constraints of its parent.
We can also pass
constraints: BoxConstraints.expand(height: 100),
constraints: BoxConstraints.expand(width: 100),
so that the
constraints will require exactly the given value in the given dimension.
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
constraints: BoxConstraints( maxHeight: 200.0, maxWidth: 100.0, ),
constraints: BoxConstraints.tight( Size(200, 100) ),
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, ),
width arguments and sets:
minWidth = width ?? 0.0, maxWidth = width ?? double.infinity, minHeight = height ?? 0.0, maxHeight = height ?? double.infinity;
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
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.
View all Courses