I’ve been using SizedBox in Flutter to add spacing between widgets by specifying width and height, like this:
SizedBox(height: 20), SizedBox(width: 10),
I recently came across the Gap widget, which seems like a more concise way to handle spacing. How can I effectively replace SizedBox with Gap in my Flutter project?
What are the main differences or advantages of using Gap over SizedBox?
>Solution :
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("Text 1"),
SizedBox(height: 20),
Text("Text 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(
"Text 1",
style: TextStyle(
fontSize: 16,
),
overflow: TextOverflow.ellipsis,
),
),
Gap Widget
this also adds spacing between widgets in the widget tree but it’s not by any means like the SizedBox 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. Still, if there is an available space that is smaller than the given one it fills the available space to avoid overflow. For this reason, it’s beneficial in making the apps responsive Example on the MaxGap widget
Row(
children: [
Text('Button one'),
MaxGap(20),
Text('Button two'),
],
),
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). SliverGap takes a fixed amount of 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,
),
),
],
),
For more detailed Info follow this link
Source: Medium