Flutter SizedBox vs LimitedBox
So what I have found is, LimitedBox
is only usable when the child is given unconstrained width/height
by its parent.
And SizedBox
simply creates a box with given width/height
and doesn't allow child to go beyond given dimensions.
Example: (LimitedBox
)
@override
Widget build(BuildContext context) {
return Scaffold(
body: LimitedBox(
maxHeight: 50, // no impact because it's child `Text` width/height isn't unconstrained
child: Text(
"A",
style: TextStyle(fontSize: 200),
),
),
);
}
Example (SizedBox
)
@override
Widget build(BuildContext context) {
return Scaffold(
body: SizedBox(
height: 50, // has impact, it won't let Text to be of more than 50 logical pixels high
child: Text(
"A",
style: TextStyle(fontSize: 200),
),
),
);
}
Note: If anyone has better answer, I am happy to accept theirs.
LimitedBox
is a SizedBox
unless the parent widget imposes a constraint.
From Doc
A box that limits its size only when it's unconstrained.
Reference
Flutter doc
LimitBox:
LimitBox works only when it's size is unconstrained If this widget's maximum width is unconstrained then its child's width is limited to [maxWidth]. Similarly, if this widget's maximum height is unconstrained then its child's height is limited to [maxHeight].
Example:
Center(
child: LimitedBox(
maxWidth: 50,
child: Container(
color: Colors.red,
width: 20,
height: 100,
)
),
),
Output:
This restricts Container
Widget with a max-width as 50 but it's going to show widget till container width which is 20.
SizeBox:
It comes with fixed sizes that restrict its child to render on the limited area. If either the width or height is null, this widget will try to size itself to match the child's size in that dimension. If the child's size depends on the size of its parent, the height and width must be provided.
Example:
Center(
child: SizedBox(
width: 50,
child: Container(
color: Colors.red,
width: 20,
height: 100,
)
),
),
Output:
This will also behave like LimitedBox
but the only difference here Container
will be rendered till width 50 of SizeBox
, it will not consider it's own width which is 20 and drawn till the parent widget.