This short post explains what const
means in Dart/Flutter and why you often see root widgets written like child: const MyApp()
not just for style, but for real performance and memory benefits.
What does const
mean?
In Dart, const
creates a compile-time constant object. A const object is immutable and can be reused by the runtime instead of creating a new instance each time the widget tree rebuilds.
const
= compile-time constant + immutable- The same instance can be reused, saving allocation & CPU work
Why can MyApp
be const
?
Typically, the root app widget (like MyApp
) is a StatelessWidget
and has no mutable properties. Because its constructor and all parameters are constant or final, it is safe to mark it const
. This tells Dart and Flutter that the widget instance will never change.
Concrete example
Compare two versions:
Without const
// main.dart (without const)
void main() {
runApp(
ChangeNotifierProvider.value(
value: authProvider,
child: MyApp(), // creates a new MyApp() object when rebuilt
),
);
}
With const
// main.dart (with const)
void main() {
runApp(
ChangeNotifierProvider.value(
value: authProvider,
child: const MyApp(), // reuses the same compile-time constant object
),
);
}
Benefits of using const
- Less memory allocation: A const widget can be canonicalized and reused, reducing allocations.
- Fewer rebuild costs: Flutter can skip re-creating or re-evaluating parts of the tree faster.
- Clear intent: It signals to other developers that this widget is immutable and fixed.
When you can't use const
If a widget has mutable/stateful properties, or accepts non-constant constructor parameters (values known only at runtime), you cannot mark it const
. For example, a widget depending on a runtime value or callback typically can't be const.
Analogy
Think of const
widgets as permanent signs nailed to a wall once installed, you reuse the same sign every time you pass by. Non-const widgets are like paper flyers: a new copy is printed every time someone needs it.
Best practice
- Use
const
wherever possible for stateless widgets and literal values (icons, texts, containers with constant args). - Prefer writing constructors and child usages with
const
e.g.child: const MyApp()
andconst Text('Hello')
. - Be mindful: don't force
const
where runtime data is needed.
Short checklist
- Is the widget a
StatelessWidget
with final properties? → You can probably useconst
. - Are all constructor arguments compile-time constant? → Good candidate for
const
. - Does marking as
const
reduce unnecessary rebuilds in your UI? → Use it.
0 Comments:
Post a Comment