Flutter : For Better Performance, Replace SizedBox with Compile-Time Constants

Vikranth Salian
2 min readMar 21, 2023

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!

--

--