Sub topic 4
Immutable widgets and const constructors
This chapter assumes you know basic Dart: classes, constructors, final fields, named parameters, and null safety. It also assumes you can run a simple Flutter app. You should have seen StatelessWidget and the build method. Here you will learn why widgets are immutable, what const does for them, and how that affects rebuilds.
Widgets are configuration, not live objects
A widget is a short-lived description of part of the UI. It is not the thing drawn on screen. Flutter creates widget objects constantly, often many times per second during an animation. It compares the new descriptions with what it already has and updates only what changed.
This only works if a widget never changes after it is created. If you want different UI, you build a new widget. You do not edit the old one.
Dart helps enforce this with final fields. Every field of a widget should be final, and the constructor sets each one.
import 'package:flutter/material.dart';
class Badge extends StatelessWidget {
const Badge({super.key, required this.label, this.highlighted = false});
final String label;
final bool highlighted;
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
color: highlighted ? Colors.amber : Colors.grey.shade300,
child: Text(label),
);
}
}Both fields are final. Once a Badge exists, its label and highlighted values stay fixed. To show a different label, a parent builds a new Badge.
The `@immutable` annotation
The Widget base class carries the @immutable annotation from package:meta. The Dart analyzer warns you if a widget subclass declares a non-final instance field. Treat that warning as an error. A mutable field on a widget can silently go stale, because Flutter may reuse or discard widget objects without telling you.
Mutable data belongs in a State object, which later chapters cover. The widget itself stays a plain, unchanging set of settings.
What `const` adds
final stops a field from being reassigned after construction. const goes further. A const constructor lets Dart build the object at compile time, and the compiler can then share one instance everywhere the same arguments appear.
You need three things to use const on a widget:
- Every field in the class is
final. - The constructor is declared with the
constkeyword. - At the call site, every argument is itself a compile-time constant.
const Text('Hello'); // OK: a string literal is a constant
const Badge(label: 'New'); // OK: Badge has a const constructor
final name = 'Ada';
// const Text(name); // Error: name is not a compile-time constantThe last case fails because name is only known at run time, even though it is final. A final variable is set once at run time. A const value must be known when the code is compiled.
Canonicalization
Dart canonicalizes constant objects. Two const expressions with identical arguments produce the same object in memory.
void main() {
const a = Badge(label: 'New');
const b = Badge(label: 'New');
print(identical(a, b)); // true
}That is the core of the performance benefit. A constant widget is allocated once, not on every build.
Why const widgets help rebuilds
When a parent rebuilds, Flutter asks each child slot whether the widget there has changed. Flutter first checks whether the new widget is the identical object as the old one. If it is, Flutter knows nothing has changed and skips rebuilding that subtree.
A const widget makes this check succeed every time. The same instance returns on each build call, so Flutter stops at that point and does no further work below it.
import 'package:flutter/material.dart';
class Dashboard extends StatefulWidget {
const Dashboard({super.key});
@override
State<Dashboard> createState() => _DashboardState();
}
class _DashboardState extends State<Dashboard> {
int _taps = 0;
@override
Widget build(BuildContext context) {
return Column(
children: [
const Text('Dashboard'),
const Icon(Icons.dashboard),
Text('Taps: $_taps'),
ElevatedButton(
onPressed: () => setState(() => _taps++),
child: const Text('Tap'),
),
],
);
}
}Each tap calls setState, and build runs again. The two const widgets at the top and the const Text('Tap') are the same instances as before, so Flutter skips them. Only Text('Taps: $_taps') is new, because it depends on _taps. It cannot be const.
The saving for one Text is tiny. The benefit grows when the constant widget sits at the top of a large subtree, because the whole subtree is skipped.
Where `const` can go
The const keyword can appear in two places, and they do different jobs.
- On the constructor declaration:
const Badge({...}). This says instances of the class can be constants. It does not force any caller to useconst. - At the call site:
const Badge(label: 'New'). This actually creates the constant instance.
Dart often lets you omit the inner const keywords. If a parent is already const, everything inside it is implicitly const.
// Both lines are equivalent. The inner widgets are implicitly const.
const Padding(
padding: EdgeInsets.all(8),
child: Text('Hi'),
);
const Padding(
padding: const EdgeInsets.all(8),
child: const Text('Hi'),
);The analyzer flags the redundant inner keywords with the unnecessary_const lint, so keep only the outermost one.
One non-constant argument ruins it
If any argument is not a compile-time constant, the whole expression cannot be const. Children inside it can still be const on their own.
Padding(
padding: EdgeInsets.all(spacing), // spacing is a runtime value
child: const Text('Hi'), // this child can still be const
);Here Padding is built fresh on each build, but const Text('Hi') is still shared.
Letting the tools help
You do not have to find every const opportunity by eye. The Flutter lints can do it for you. Enable these in analysis_options.yaml:
include: package:flutter_lints/flutter.yaml
linter:
rules:
prefer_const_constructors: true
prefer_const_constructors_in_immutables: true
prefer_const_literals_to_create_immutables: trueprefer_const_constructorsreports a constructor call that could beconstbut is not.prefer_const_constructors_in_immutablesreports a widget class whose constructor could beconstbut is not declared that way.prefer_const_literals_to_create_immutablesreports list and map literals, such aschildren: [...], that could be constant.
Your IDE can apply the quick fix for each report. Running dart fix --apply applies many of these fixes across a project at once.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| A non-final field in a widget | The analyzer warns that the class is `@immutable`. A `const` constructor is an error. | Make the field `final`. Put changing data in `State`. |
| Forgetting `const` on the constructor | Callers cannot write `const MyWidget()`, and every build allocates a new instance. | Add `const` to the constructor. |
| Using `const` with a runtime value | Compile error: the argument is not a constant expression. | Drop `const` on that widget. Keep it on constant children. |
| Expecting `const` to stop a needed update | Not a real problem. A const widget depends only on its arguments, so it has nothing new to show. | Pass changing data through a non-const widget. |
A subtle case: `const` and inherited data
A const widget can still change what it displays. The rebuild skip applies to the parent's rebuild. If the widget reads an inherited value, such as Theme.of(context), Flutter marks it for rebuild when that value changes, even though the widget instance is identical.
import 'package:flutter/material.dart';
class ThemedLabel extends StatelessWidget {
const ThemedLabel({super.key});
@override
Widget build(BuildContext context) {
final color = Theme.of(context).colorScheme.primary;
return Text('Themed', style: TextStyle(color: color));
}
}Using const ThemedLabel() is safe. When the theme changes, ThemedLabel rebuilds anyway, because it registered a dependency on the theme through its BuildContext. So const removes needless rebuilds, but it does not hide real changes.
Hot reload and const
During hot reload, Flutter re-runs build methods, but it does not re-evaluate constant objects that were already created. If you change the arguments of a const expression and the change seems to have no effect, try a hot restart. A hot restart re-creates every object from scratch.
Putting it together
Use these rules for each widget you write:
- Declare every field
final. - Declare the constructor
constwhenever all fields arefinal. - Write
constat the call site whenever every argument is a compile-time constant. - Keep changing data in
State, not in the widget. - Split a large
buildmethod so the constant parts become their ownconstwidgets.
Exercise
This code does not compile. Name the problem and give two different ways to fix it. class Price extends StatelessWidget { const Price({super.key, required this.amount}); double amount; @override Widget build(BuildContext context) => Text('$amount'); }
Show answer
The field amount is not final, so the class cannot have a const constructor. A widget is immutable, so all its fields must be final. Fix 1: change the field to final double amount;. Fix 2: remove const from the constructor, though this gives up the rebuild savings and the analyzer will still warn that the class is @immutable. Fix 1 is the correct one. Mutable data belongs in a State object.
Exercise
In the build method below, which widgets can be marked const, and which cannot? Explain why.
Widget build(BuildContext context) {
final user = fetchUserName();
return Column(
children: [
Text('Welcome'),
Text(user),
Icon(Icons.person),
],
);
}
Show answer
Text('Welcome') and Icon(Icons.person) can be const, because their arguments are compile-time constants. Text(user) cannot, because user is a runtime value. The children list also cannot be const, because one element is not constant. Each constant child can still be marked const individually.
Exercise
A const Badge(label: 'New') appears in a parent's build method. The parent calls setState. Does Badge's build method run again? What if Badge reads Theme.of(context)?
Show answer
If Badge does not read any inherited value, its build does not run again. The parent produces the identical instance, so Flutter skips that subtree. If Badge reads Theme.of(context), it depends on the theme and rebuilds only when the theme changes, not simply because the parent called setState.