Black Friday Sale

Flutter Foundations Course

Buy now and get 33% off the regular price!

View Course

How to replace SizedBox with compile-time constants for better performance

One very common use case for SizedBox is when adding a gap between widgets inside a Row or Column.

In practice, this often leads to code that looks like this:

Column( children: const [ Text('Spacing is a good idea in UX design.'), SizedBox(height: 16), Text('It makes your UI less cluttered.'), ] )

or like this:

Row( children: [ const Text('Image Preview:'), const SizedBox(width: 16), CachedNetworkImage(imageUrl: product.imageUrl), ] )

There's nothing wrong with the code above.

However, it's very easy to forget the const modifier when needed.

And having to type SizedBox(height: someValue) many times over is a bit too verbose.

So here's a little tip to improve things.

Defining gaps as const widgets

In a separate file, we can define all the SizedBoxes we need as compile time constants, using multiples of 4 pixels:

// gaps.dart const gapW4 = SizedBox(width: Sizes.p4); const gapW8 = SizedBox(width: Sizes.p8); const gapW12 = SizedBox(width: Sizes.p12); ... const gapW64 = SizedBox(width: Sizes.p64); const gapH4 = SizedBox(height: Sizes.p4); const gapH8 = SizedBox(height: Sizes.p8); const gapH12 = SizedBox(height: Sizes.p12); ... const gapH64 = SizedBox(height: Sizes.p64);

Then, we can use them whenever we need:

// don't forget to import gaps.dart! Column( children: const [ Text('Spacing is a good idea in UX design.'), gapH16, Text('It makes your UI less cluttered.'), ] ) Row( children: [ const Text('Image Preview:'), gapW16, CachedNetworkImage(imageUrl: product.imageUrl), ] )

Once again: your code will be more performant because all the gaps above are hardcoded as compile-time constants.

And you'll have less typing to do, which is always a nice win! 👌

Why multiples of 4?

If you prefer, you can use multiples of 8.

The main point is that this will make your UI look more consistent, by giving you a strict set of values to choose from.

Happy coding!

Want More?

Invest in yourself with my high-quality Flutter courses.

The Complete Dart Developer Guide

The Complete Dart Developer Guide

Learn Dart Programming in depth. Includes: basic to advanced topics, exercises, and projects. Fully updated to Dart 2.15.

The Complete Flutter Course Bundle

The Complete Flutter Course Bundle

Learn about State Management, App Architecture, Navigation, Testing, and much more by building a full-stack Flutter eCommerce app on iOS, Android, and web.

Flutter Animations Masterclass - Full Course

Flutter Animations Masterclass - Full Course

Master Flutter animations and build a completely custom habit tracking application.