SizedBox Vs Gap: The Complete Guide for Flutter Developers
Introduction
The Spacing between the widgets and the Sizing of the widgets are very important to build your layout in Flutter. the SizedBox and Gap are two commonly used ways to add space between your app widgets in Flutter. So what is the Difference Between SizedBox and Gap?
Let's understand each one of them and how they work.
SizeBox Widget
It's the most frequently used one as we just set the height and the width which allows us to control the space and dimensions from it, it's more likely to the Container widget but with fewer Properties.
- The following code snippet makes a 20px height separator between two widgets
Column(
children: [
Text("Widget 1"),
SizedBox(height: 20),
Text("Widget 2"),
],
)
We also use it to determine the size of the child widget
- The following code snippet gives a height and width of 100px to the child widget
SizedBox(
width: 100,
height: 100,
child: Text(
"Widget 1",
style: TextStyle(fontSize: 16,),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
);
Gap Widget
this also adds spacing between widgets in the widget tree but it's not by any means like the sized box or the container as it only takes size and automatically determines the width and height also it determines the direction of the space according to the parent widget so it's much easier to deal with
There are two types of Gap widgets:
MaxGap Widget
this widget fills the space between the widgets according to the given size but if there is an available space that is smaller than the given one it fills the available space to avoid overflow and for this reason, it's very helpful in making the apps responsive
- Example on the MaxGap widget
Row(
children: [
Text('Button 1'),
MaxGap(20),
Text('Button 2'),
],
)
SliverGap Widget
this widget is used to separate between the sliver widgets the sliver widgets are used to make custom scroll effects (more on this in the following tutorials). the SliverGap takes fixed amount space.
- The following code snippet adds a vertical space between slivers
CustomScrollView(
slivers: [
SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) {
return Text('Item $index');
},
childCount: 10,
),
),
SliverGap(height: 32.0),
SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) {
return Text('Item ${index + 10}');
},
childCount: 10,
),
),
],
)
Summary
To sum things up, the SizedBox is a built-in widget in Dart while the Gap is a package that we can add to our project so it's all up to you if you want to to save time and decrease your errors as you may mistakingly add a SizedBox with a width property in a Column parent widget you should use the Gap but if you can handle errors and have enough time you may use the SizedBox
Subscribe to my newsletter
Read articles from Omar Ashraf directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Omar Ashraf
Omar Ashraf
Junior Computer Engineering Student at Ain Shams University.