Why is it good practice to use `const` constructors in Flutter widgets?
Show answer — try answering out loud first
A widget created with const is built only once and Flutter reuses it (canonicalization), instead of recreating it on every build. Also, when the parent widget rebuilds, Flutter can skip rebuilding a const subtree because it knows it didn't change. This reduces work and improves performance.
In Flutter, build is called a lot. Every time, new widgets are created. If a widget doesn't depend on any data that changes, recreating it over and over is a waste.
When you mark a widget as const:
- A single instance is created that Flutter always reuses (two
const Text('Hi')are literally the same object in memory). - When rebuilding the parent, Flutter compares and detects that the
constwidget is identical to the previous one, so it doesn't rebuild that subtree.
It's one of the easiest and highest-impact optimizations: basically "free", you just have to write const.
import 'package:flutter/material.dart';
class Screen extends StatelessWidget {
const Screen({super.key});
@override
Widget build(BuildContext context) {
return Column(
children: const [
// These widgets never change: mark them const.
// Flutter creates them once and reuses them on every build.
Text("Fixed title"),
SizedBox(height: 8),
Icon(Icons.star),
],
);
}
}
If Screen rebuilds 100 times, those three const widgets aren't recreated: the same instance is reused.
Not being able to use const because an intermediate value doesn't allow it, and not noticing. It only takes a single child depending on a runtime variable for the parent's const to become impossible. It's also common to forget const entirely: Flutter's linter (prefer_const_constructors) usually warns you, and it's worth listening to it.
"A
constconstructor makes the widget get created once and lets Flutter reuse it, instead of recreating it on everybuild. Also, when the parent rebuilds, Flutter detects that aconstsubtree didn't change and skips rebuilding it. It's an almost-free optimization: I just writeconston the widgets that don't depend on changing data. That's why Flutter's linter insists so much onprefer_const_constructors."
Why can const Text('Hi') be more efficient than Text('Hi') even though they show the same thing?
See answer
Because const Text('Hi') is a compile-time constant: Flutter creates a single instance and reuses it on every rebuild, and it can skip rebuilding that subtree when it detects it's identical. Text('Hi') without const creates a new object on every build, forcing Flutter to compare it and potentially redo more work.