Better Performance with const Widgets in Flutter

Ruben Aster
5 min readMay 17, 2023

--

Supercharge your Flutter apps with const widgets and discover how to have the linter watch your back

When it comes to crafting performant apps using Flutter, it’s all about the widgets. These are the bread and butter of any Flutter application, the building blocks that shape your user interface and guide user interaction.

But here’s something you might not know: not all widgets are created equal. In the magical world of Flutter, const widgets reign supreme, and they’re ready to supercharge your apps. Buckle up, we’re about to dive into the world of const widgets! And make sure you don’t skip the linter section at the end of this article!

Unmasking the const Widgets

Before we go any further, let’s clear up what we mean by “const” widgets. Simply put, a const widget is an instance of a class that you’re declaring won’t change. You’re letting Flutter know that once you’ve set this widget, it’s going to stay the same throughout the lifetime of the app.

Why const Widgets are your Secret Weapon

Now, you might be asking, why does it matter if a widget changes or not? Well, when you make use of const widgets, Flutter can optimize your app’s performance and memory usage, essentially making your apps faster and more efficient. Plus, const widgets are loaded on startup, meaning your app’s runtime performance is as smooth as a freshly iced cake.

  1. Speeding Up Build Time: When you use a const widget, you’re essentially telling Flutter, “Hey, this widget isn’t going to change, so you can build it once and use it as many times as you need.” This is a huge time-saver when Flutter is drawing the UI. It doesn’t have to create new widget instances every time the framework rebuilds the widget tree. Instead, it uses the existing instance, reducing both CPU usage and the time it takes to render your widgets on screen.
  2. Reducing Memory Footprint: Const widgets are not just about saving time; they’re also about saving space. In Flutter, every widget is an object, and objects take up memory. By using const widgets, you’re creating a single instance of the widget object. This instance can be reused every time the widget appears in the widget tree, reducing the overall memory usage of your app.
  3. Eliminating Runtime Hiccups: Because const widgets are built at compile-time, they are loaded into memory when your app starts up. This means that, during the runtime of your app, these widgets are readily available for use. There’s no need for any on-the-fly object creation or garbage collection related to these widgets. This leads to smoother scrolling and animations, as these operations don’t have to compete with widget building tasks.
  4. Predictability and Debugging: Const widgets are immutable. This means once they are defined, they can’t be changed. This immutability provides a degree of predictability in your code, making your app more stable. It also makes debugging easier, as you know that once a const widget is created, its state can’t be altered, ruling it out as a cause of any state-related bugs.

When to call upon the Power of const

Keep in mind, not all widgets are ripe for the const treatment. Only those widgets that don’t change — those with no mutable properties — can be made const. In most cases, these are the stateless widgets that rely only on their constructor parameters.

Harnessing the Power of const

To tap into the power of const, simply add the const keyword before the widget constructor. It's like a secret handshake that unlocks the widget's full potential.

const Text('Hello, Flutter!');

Walking through the Good, the Bad, and the const

To bring this to life, let’s look at some examples of when to use const and when not to.

Example: BoxDecoration

❌ Bad:

Container(
decoration: BoxDecoration(
color: Colors.blue,
),
child: Text('Welcome to Flutter!'),
)

✔️ Good:

Container(
decoration: const BoxDecoration(
color: Colors.blue,
),
child: const Text('Welcome to Flutter!'),
)

Now let’s consider an example where we’re creating a list of Icon widgets inside a loop.

❌ First, let’s look at an example without using const:

class StarList extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: 100,
itemBuilder: (context, index) {
return Icon(Icons.star, color: Colors.yellow);
},
);
}
}

In this example, a new Icon instance is created for each item in the ListView. This isn't very efficient since it requires allocating memory and initializing each widget separately.

✔️Now let’s see how we can optimize this with the const keyword:

class StarList extends StatelessWidget {
const StarList({super.key});

@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: 100,
itemBuilder: (context, index) {
return const Icon(Icons.star, color: Colors.yellow);
},
);
}
}

In this updated example, we’re still adding 100 Icon widgets to the ListView, but by using the const keyword, Flutter reuses the same Icon instance for each item. This significantly improves performance, as memory allocation and widget initialization only happen once, rather than 100 times.

Enlist the Linter to catch missing consts

As if const widgets weren’t cool enough on their own, you can actually set your linter to give you a heads up when you’ve missed a chance to use them. By adding a couple of simple rules to your analysis_options.yaml file, you'll get a warning whenever a const could be used but isn't.

linter:
rules:
- prefer_const_constructors
- prefer_const_literals_to_create_immutables

The prefer_const_constructors rule will warn you when a const constructor is available but not being used, while the prefer_const_literals_to_create_immutables rule will warn you when you're using a non-const list or map literal containing only const elements.

Once you’ve added these rules, the linter will automatically check your code for missing const widgets and provide warnings. This way, you’ll never miss an opportunity to wield the power of const magic in your Flutter apps!

Remember to cast a glance at the official Dart lint rules that can help you write cleaner and more efficient code.

Conclusion

In the world of Flutter, const widgets are more than just a nice-to-have. They’re a powerful tool in your Flutter toolkit, ready to help you craft high-performance apps that have lighter memory footprints, smoother runtime, and easier debugging.

So, remember to use const widgets when you code your next Flutter app. It’s a small step that makes a big difference.

--

--

Ruben Aster

Azure Cloud Solution Architect, Freelancer, Consultant, Germany