Flutter Box Constraints 101: The Basics
The really simple explanation…
Summary
Box constraints are quite important in Flutter as they determine how exactly a UI widget is drawn on the screen compared to dimensions given in the code.
Explanation
If for example, you container has a dimension of 900 x 500 but when you run the code on your simulator, you see that its actually smaller than what you have intended to, this is due to the box constraints coming in from the parent widget. If the parent of the container is a scaffold, then the box constraint coming in from the scaffold to the container would be the screen dimensions.
IMP: box constraints are passed down by the parent to the child automatically by the framework.
Consider the basic widget tree, the constraints are passed in orange font:

This is the tree for the following simple flutter code:
So, lets break it down:
- The root Scaffold is getting its box constraints from the Flutter framework, even if you don’t specify any dimensions, in fact you can’t specify any dimensions to scaffold widget.
- When you add container widget as a child, the box constraints are passed down from the parent to the child, and in this case, from scaffold to the container. So, what does that mean?
- The box constrains pretty much restricts the child widget from becoming any bigger than the constraints. If you see the sample code, the containers width and height are greater than the phone’s dimensions(in portrait mode) but when its actually rendered or drawn on the screen, its less than that, maxing out at the box constraints passed down by the parent.
So why does this happen? For responsiveness. Different screens have different dimensions and this is one of the many things the framework does for you to make sure your code runs smoothly on different screen sizes.
Here is something interesting, check this code out, we change the height and width of the container to infinity. What do you think happens here?
Yup, the box constraints passed down from scaffold make sure that the container doesn’t get bigger than screen dimensions.
In the next post, I will talk about constraints passed down by the two core UI widgets Column and Row, which are the blood and bones of any UI framework and how the box constraints work with them. Its really interesting and also these posts sets up nicely for explaining the following errors and their siblings:
- BoxConstraints forces an infinite height.
- RenderFlex children have non-zero flex but incoming height constraints are unbounded.
Don’t worry, I will make it really easy for you to understand these errors and once you are done reading this series, you will be really comfortable with fixing them when you see them in you code :)
See in you next post!
Checkout the native app I created using flutter. Currently only deployed to Apple’s App Store. Google’s Play Store is taking more time to review because of Covid delays.
Also, if possible, give me a follow on twitter: