Sub topic 4
Use const to reuse widget instances
What you will learn
This chapter assumes you know how setState marks an element dirty and calls build (covered earlier in this tutorial), and that you can run a Flutter app in debug mode. By the end you will be able to:
- Explain why an identical widget instance lets Flutter skip a subtree.
- Place
constwhere it actually produces a shared instance. - Recognize the cases where
constis impossible or does not help. - Verify the effect by counting
buildcalls.
Why const prevents rebuilds
When a parent rebuilds, its build method returns a new tree of widget objects. Flutter then walks the existing element tree and compares each old child element with the new widget at the same position. This step is Element.updateChild, and it follows a simple decision order:
- If the new widget is
identicalto the one the child element already holds, Flutter keeps the element and does nothing else. It does not callupdateand does not callbuildon that child or anything below it. - If the widget is a different instance but has the same
runtimeTypeandkey, Flutter callsupdateon the element, which schedules a rebuild of that element. - Otherwise, Flutter removes the old element and inflates a new one.
Step 1 is the one const unlocks. Widget does not override ==, so two widgets are equal only when they are the same object. Comparing field values never happens. The only way to get an identical instance is to hand Flutter the same object again.
A const expression gives you that. Dart canonicalizes compile-time constants: every const ExpensiveHeader() in your program evaluates to one shared object. Each time build runs, the expression returns that same object, so step 1 applies.
A worked example you can run
This app counts how often each child builds. Tapping the button calls setState on the parent. Only the non-const child should report a rebuild.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: ConstDemo()));
class BuildLogger extends StatelessWidget {
const BuildLogger({super.key, required this.label});
final String label;
@override
Widget build(BuildContext context) {
debugPrint('build: $label');
return Padding(
padding: const EdgeInsets.all(8),
child: Text(label),
);
}
}
class ConstDemo extends StatefulWidget {
const ConstDemo({super.key});
@override
State<ConstDemo> createState() => _ConstDemoState();
}
class _ConstDemoState extends State<ConstDemo> {
int _taps = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const BuildLogger(label: 'const child'),
BuildLogger(label: 'non-const child'),
Text('Taps: $_taps'),
ElevatedButton(
onPressed: () => setState(() => _taps++),
child: const Text('Tap'),
),
],
),
);
}
}On launch, the console prints both labels once. After each tap, it prints only build: non-const child. The parent's build created a new BuildLogger object for the second slot, so step 2 applied. The first slot received the canonical constant, so step 1 applied.
The saving grows with the subtree. If ExpensiveHeader contains 200 widgets, a single const skips all of them, not just the root.
Where const actually applies
A constructor call can be const when the class has a const constructor and every argument is itself a compile-time constant. Some forms that appear in real screens:
| Expression | Const? | Reason |
|---|---|---|
| `const SizedBox(height: 16)` | Yes | Literal arguments |
| `const Text('Like')` | Yes | String literal |
| `Text('Likes: $_likes')` | No | Interpolates runtime state |
| `const Icon(Icons.favorite)` | Yes | `Icons.favorite` is a static const |
| `Icon(icon)` where `icon` is a parameter | No | Value known only at runtime |
| `const EdgeInsets.all(8)` | Yes | Const constructor, literal argument |
| `ElevatedButton(onPressed: () {...})` | No | A closure is not a constant |
Nested constants
Inside a const context you do not repeat the keyword. Once the outer constructor is const, everything beneath it is implicitly const:
const Card(
child: Padding(
padding: EdgeInsets.all(16),
child: Column(
children: [
Text('Title'),
SizedBox(height: 8),
Text('Body'),
],
),
),
)Only the outer Card needs the keyword. A single non-constant value anywhere inside breaks the chain for the parts above it. The outer widget becomes non-const, and you must add const to the constant parts one by one.
Making your own widgets const-friendly
A custom widget can be constructed with const only if it declares a const constructor and all of its fields are final. Without the constructor, callers cannot use the keyword, even with literal arguments:
class ExpensiveHeader extends StatelessWidget {
const ExpensiveHeader({super.key, this.title = 'Dashboard'});
final String title;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(16),
child: Text(title, style: Theme.of(context).textTheme.headlineMedium),
);
}
}Add const to every widget constructor you write. It costs nothing and lets callers opt in later.
Reusing instances without const
Some subtrees depend on values known only at runtime, so the compiler cannot make them constant. You can still get step 1 by creating the widget once and keeping the reference. A common place is a State field:
class _ReportScreenState extends State<ReportScreen> {
int _selected = 0;
late final Widget _chart = ChartView(data: widget.data);
@override
Widget build(BuildContext context) {
return Column(
children: [
Tabs(
selected: _selected,
onChanged: (i) => setState(() => _selected = i),
),
_chart, // same instance on every build
],
);
}
}This is a manual form of the same technique, and it has a cost: if widget.data changes, _chart will not notice. You would have to rebuild the field in didUpdateWidget. When the cached object depends on anything that changes, prefer splitting the screen into smaller widgets (covered in the next chapters). The builder child parameter, covered later, is the framework's own safe version of this pattern.
What const does not do
const removes rebuilds that come from a parent. It does not stop a widget from rebuilding for its own reasons.
- Inherited dependencies still fire. A const widget whose
buildcallsTheme.of(context),MediaQuery.sizeOf(context), orcontext.watchregisters a dependency. When that inherited value changes, the framework marks the element dirty directly, and it rebuilds despite being const. TheExpensiveHeaderabove rebuilds when the theme changes, which is correct behavior. - Its own state still works. A const
StatefulWidgetcan callsetStateon its ownStateobject. The widget instance is shared, but each element has its own state. - A const parent hides its descendants' parent-driven updates. If a const widget wraps a subtree, nothing inside can change unless it has its own state or inherited dependencies. That is the point, but it surprises people who expect a value passed through globals to update.
- It does not reduce the cost of the first build. The savings come on later frames only.
Hot reload
Changing a constant's definition, such as a default argument, may not appear after a hot reload for already-created constants. If a const widget seems stuck on an old value, do a hot restart.
Enforcing const with lints
Hunting for missing const by eye does not scale across a large codebase. The Dart analyzer has lints that flag the omissions and offer quick fixes. Enable them in analysis_options.yaml:
linter:
rules:
- prefer_const_constructors
- prefer_const_constructors_in_immutables
- prefer_const_declarations
- prefer_const_literals_to_create_immutablesprefer_const_constructorsflags a constructor call that could beconst.prefer_const_constructors_in_immutablesflags a widget class whose constructor could beconstbut is not.prefer_const_literals_to_create_immutablesflags list literals, such aschildren: [...], that could be const.
The IDE can apply these fixes across a whole file or project. Review the diff after a bulk fix. It only adds keywords, but a lint that fires on code you expected to be dynamic points to a spot worth looking at.
Common mistakes
- Adding
constto the wrong layer.const Padding(padding: EdgeInsets.all(8), child: Text(title))does not compile, becausetitleis not constant. The fix is to putconston the pieces that are constant (padding: const EdgeInsets.all(8)), not to fight the error. - Assuming a const parent makes children cheap in the same frame as a state change. Const children skip rebuilds only when nothing inside them depends on the changed state.
- Expecting
constto help with a list of generated items.ProductTile(product: item)takes a runtime value, so it cannot be const. Use keys and lazy lists for that case. - Forgetting that
Keyarguments must be const too.const Foo(key: ValueKey(id))fails whenidis a variable. This is another sign that the widget should not be const. - Reaching for const instead of fixing scope. If the state that changes lives at the top of a huge
build, dozens ofconstkeywords are a patch. Moving the state down is the structural fix. The next chapters cover that, and the two techniques work together.
Checking your work
You can confirm that const helped in two ways. First, add a debugPrint inside a suspect widget's build, as in the example above, and watch whether it prints after the parent rebuilds. Second, turn on debugPrintRebuildDirtyWidgets (from the measuring chapter) and compare the list of rebuilt widgets before and after the change. A widget that moved from the list to absent was skipped by identity.
Summary
Flutter skips a child element when it receives the identical widget instance. const constructors canonicalize widgets so every build returns the same object. This only works when the class has a const constructor and all arguments are compile-time constants. Const does not block rebuilds driven by the widget's own state or by inherited dependencies. Enable the lints so the omissions are found automatically, and cache instances manually only when the cached subtree cannot depend on changing data.
Exercise
In the demo app, you change const BuildLogger(label: 'const child') to BuildLogger(label: 'const child') by removing the keyword. What does the console print after one tap, and why?
Show answer
It prints build: const child and build: non-const child. Without const, the parent's build creates a new BuildLogger object on every call. The new object is not identical to the one the element holds, so updateChild calls update and the element rebuilds. Both children behave the same way now.
Exercise
A const SummaryCard() calls Theme.of(context) inside its build. The user switches from light to dark theme. Does the card rebuild, and why?
Show answer
Yes. Theme.of(context) registers the card's element as a dependent of the theme's inherited widget. When the theme changes, the framework marks that element dirty directly, so identity of the widget instance does not matter. const only blocks rebuilds caused by the parent passing a new widget.
Exercise
You write const Padding(padding: EdgeInsets.all(8), child: Text(userName)) and the compiler reports an error. Explain the cause and give a corrected version that keeps as much const as possible.
Show answer
userName is a runtime value, so Text(userName) is not a constant, and a const Padding cannot hold a non-const child. Remove const from Padding and keep it on the constant argument: Padding(padding: const EdgeInsets.all(8), child: Text(userName)).