Use of SizedBox Widget in Flutter

SizedBox Widget

Hey guys, today will see an interesting widget that is SizedBox Widget. Let's get started.

Sometimes, you know exactly what you want, like if there is any button and we want that button should be 200 pixels wide, not more or less. That's easy!

Just wrap the button with a SizedBox and give the width in pixels. Not only width, but you can also provide height for complete control of the size. You will get perfect pixels.

SizedBox(
width: 200,
height: 100,
child: MyButton(),
),

SizedBox is a widget with a specific size that directs its child to also have that size.



SizedBox in flutter

Guys, here it is a common question.

What if you tell the SizedBox to have an infinite size in a direction, does it go to infinity and beyond?

SizedBox(
width: double.infinity,
height: 100,
child: MyButton(),
),

The answer is No, unfortunately. It just expands as much as its parent allows. If you put infinity in both dimensions, then the child fills the available space.

SizedBox(
width: double.infinity,
height: double.infinity,
child: MyButton(),
),


SizedBox with expanded dimensions

There's a handy shortcut for this: SizedBox.expand.

SizedBox.expand(
child: MyButton(),
),

You can use SizedBox without a child. It will not render anything, but will still take up the space. Using SizedBox widget is a great idea for adding gaps between widgets.

Column(
children: [
MyButton(),
SizedBox(height: 100),
OtherButton(),
]
),


Empty SizedBox

Just like SizedBox.expand, we have another property SizedBox.shrink. Let's take a look.

Usually, it is used to make a box where the size is as little as its parent allows. For a better understanding see the below example.

 ConstrainedBox(
constraints: new BoxConstraints(
minHeight: 20.0,
minWidth: 80.0,
),
child: SizedBox.shrink(
child: RaisedButton(
color: Colors.blue,
child: Text('Hello !', style: TextStyle(color: Colors.white)),
onPressed: () {},
),
)
)



SizedBox.shrink

I hope this article will assist you a lot in understanding SizedBox Widget. In case you have got any inquiries, ask in a comment section below.

Previous
Next Post »