Comparison of widgets that prevent overflow
I have been trying out which widget fits best for one of the components of my app. The objective is to prevent the component from throwing an overflow error when the screen size changes. For instance, a SizedBox
widget gives my a favourable result when viewed on ordinary screen dimensions.
SizedBox(
height: 100.0,
child: Row(
// items
)
)
However, if I shrink the screen size, we will see a error as follows.
This error occurs because when the screen size reduces, the text tries to wrap to next lines but due to the limit of 100 pixels set on the Row
height, there is no space remaining for more lines and Flutter thinks this is unintended behaviour and raises an error to alert the developer.
My aim is to support variable screen sizes and prevent this error from happening. In this blog post, I look at various widgets that give me various results, and will choose the best out of them.
SizedOverflowBox
The SizedOverflowBox
does allow crunching of the screen into a tiny width without giving any error. It does not impose a size on its children like SizedBox
does, which is the reason why the children don’t expand to meet the parent’s size. Instead, as its children become bigger they automatically demand more height which is provided to them till they grow to the mentioned pixel limit.
SizedOverflowBox(
size: const Size.fromHeight(100.0),
child: Row(
// items
)
)
LimitedBox
There are two ways to specify a LimitedBox
, with maxHeight
or maxWidth
or without. In both cases, the normal screen view looks like this
When we don’t specify maxHeight
or maxWidth
and squeeze the screen width, we see this appearing
Clearly, this shows that the child widgets are making space for themselves inside the Row
, and expanding the total height of the Row
to make room.
Specifying maxHeight
parameter restricts the height to the specified amount of pixels and also raises an error on overflow.
FittedBox
Using FittedBox
looks like this
What it brings to the table is its ability to scale its children based on different screen sizes, which is a favourable attribute. But it doesn’t allow its children to take up maximum height from the start.
IntrinsicHeight
IntrinsicHeight
widget solves the problem. In order to use intrinsic height in the way it is shown in the screenshot, the children must be made to expand infinitely.
But as the documentation suggests, it causes a relatively expensive computation. So use with care.