Chapter 2 · Practice 3 of 5
Use const constructors wherever you can
Why it matters
The Flutter docs say to use const constructors on widgets as much as possible, since they allow Flutter to short-circuit most of the rebuild work. A const widget is created once at compile time and reused, so when its parent rebuilds, Flutter can skip it.
- Give your own widgets a
constconstructor when all their fields are final. - Add
constat call sites:const SizedBox(height: 16),const Icon(Icons.add). - Let the lints from
flutter_lintspoint out the places you missed.
This is one of the few performance tips that costs nothing and has no downside.
Do
- Declare
constconstructors on widgets with only final fields - Accept the analyzer's "prefer const" fixes in bulk
Avoid
- Adding a non-final field to a widget just to mutate it later
Example
class SectionTitle extends StatelessWidget {
const SectionTitle(this.text, {super.key});
final String text;
@override
Widget build(BuildContext context) =>
Text(text, style: Theme.of(context).textTheme.titleMedium);
}
// At the call site
const SectionTitle('Recent orders');