Skip to content

πŸ§‘πŸ»β€πŸš€ Easily add spaces between widgets in Flutter using the Gap package

 at 

I use SizedBox very frequently to add spaces between widgets in Flutter. Because I use it so often, it becomes tedious to create a SizedBox widget and set its height or width properties repeatedly.

I found dhat there is an easier way using Gap package which provides Gap and SliverGap widgets to add spaces between widgets. The Gap widget is used to add vertical spaces between widgets, and the SliverGap widget is used to add vertical spaces between Sliver widgets. The magical part is that you don’t need to set the height or width property; you just give a double value as a positional parameter, and it will automatically add a horizontal space if used in a horizontally laid out widget (like a Row) and a vertical space if used in a vertically laid out widget (like a Column).

Here is an example of the Gap widget:

Column(
  children: [
    // Adds a vertical space
    Text('Hello'),
    Gap(10),
    Text('World'),

    // Adds a horizontal space
    Row(
      children: [
        Text('Hello'),
        Gap(10),
        Text('World'),
      ],
    ),
  ],
)

Or if you are using Sliver widgets:

CustomScrollView(
  slivers: [
    SliverList(
      delegate: SliverChildListDelegate(
        [
          Text('Hello'),
          // Adds a vertical space
          SliverGap(10),
          Text('World'),
        ],
      ),
    ),
  ],
)

If you are like me and think, β€œUsing SizedBox without const is not a big performance loss,” and you can live without it, you can create a num extension to make it easier to use the Gap widget. Here is the extension that I created:

extension NumX on num {
  Gap get gap => Gap(this);
  SliverGap get sliverGap => SliverGap(this);
}

Now, you can use the gap property on any num value to create a Gap widget. Here is an example:

Column(
  children: [
    Text('Hello'),
    10.gap,
    Text('World'),

    Row(
      children: [
        Text('Hello'),
        10.gap,
        Text('World'),
      ],
    ),
  ],
)

Or if you are using Sliver widgets:

CustomScrollView(
  slivers: [
    SliverList(
      delegate: SliverChildListDelegate(
        [
          Text('Hello'),
          10.sliverGap,
          Text('World'),
        ],
      ),
    ),
  ],
)

I hope you find this package as useful as I do. If you would like to thank the author of the package, you can do so by giving a star to the package on pub.dev or to the repository on GitHub.



Subscribe to the newsletter
Kamran Bekirov

I'm Kamran Bekirov, a Serial Flutter Developer.
Built over 70 mobile apps for clients and myself.
Currently building UserOrient as a SaaS product.
Personal mobile apps: LibroKit, Beyt
Open-source projects: logarte, versionarte
Reach me on: X, LinkedIn, Instagram, GitHub