This tutorial shows you how to use OverflowBox
widget in Flutter.
With UnconstrainedBox
, you can impose different constraints to a child widget. However, the size of the child cannot be bigger than its parent's constraints, like the below example.
Container(
width: 100,
height: 100,
color: Colors.black38,
child: SizedBox(
width: 300,
height: 50,
child: RaisedButton(
color: Color.fromARGB(100, 0, 128, 128),
child: Text('Woolha', style: TextStyle(color: Colors.white)),
onPressed: () {},
),
),
)
Output:
What if you want a child widget to be bigger than the constraints of its parent. You can use a widget called OverflowBox
. It allows you to impose different constraints to the child and makes it possible for the child to overflow its parent.
Using OverflowBox
Here's the constructor of OverflowBox
const OverflowBox({
Key key,
this.alignment = Alignment.center,
this.minWidth,
this.maxWidth,
this.minHeight,
this.maxHeight,
Widget child,
})
If you define maxWidth
and/or maxHeight
, the values must be greater or equal than the parent's width and height constraints respectively. Otherwise an assertion error will be thrown.
In the below example, we set the maxWidth
to 400.
Container(
width: 100,
height: 100,
color: Colors.black38,
child: OverflowBox(
maxWidth: 400,
child: SizedBox(
width: 300,
height: 50,
child: RaisedButton(
color: Color.fromARGB(100, 0, 128, 128),
child: Text('Woolha', style: TextStyle(color: Colors.white)),
onPressed: () {},
),
),
),
)
Output:
As the result, the width of the child can be greater than 100 (the parent's width constraint). The value of maxWidth
is the maximum allowed width, which means it doesn't set the width of the child to be equal to the value. The same also applies for maxHeight
which needs to be set if you want the height of the child to be greater than the parent's height constraint.
From the output of the above example, you can see that the height of the child is the same as the parent's height constraint. If you want to make it smaller, you need to set minimumHeight
value. In case you want the width to be smaller than the parent's height constraint, the property you need to set is minimumWidth
.
Container(
width: 100,
height: 100,
color: Colors.black38,
child: OverflowBox(
maxWidth: 400,
minHeight: 10,
child: SizedBox(
width: 300,
height: 50,
child: RaisedButton(
color: Color.fromARGB(100, 0, 128, 128),
child: Text('Woolha', style: TextStyle(color: Colors.white)),
onPressed: () {},
),
),
),
)
Output:
That's how to use OverflowBox
widget in Flutter. You can also read about
SizedBox
, a widget used for setting width and height constraints.ConstrainedBox
, a widget used for imposing additional constraints to its child.UnconstrainedBox
, a widget that imposes no constraints on its child.