The analyzer keeps telling me to add const, and I read that rebuilding is cheap. How much does it matter, and what is the practical way to stop rebuilds spreading through a big screen?
DEV3 Developer Forum
Does using const widgets really improve Flutter performance, and how do I reduce unnecessary rebuilds?
Ask a question
Every post is reviewed first. Usually reviewed within 24 hours.
dev3 ·
0
1 reply
dev3 · Accepted answer
What const does
A const widget is created once at compile time and the same instance is reused. When a parent rebuilds, Flutter sees the identical instance and skips rebuilding that whole subtree. For small trees the gain is tiny, but in large screens it removes a lot of work every frame, and the lint costs nothing.
Where the real gains come from
- Keep setState low. If a counter changes, put it in a small StatefulWidget instead of the page root.
// bad: the whole Scaffold rebuilds for one number
setState(() => _count++);
// better: isolate the changing part
class CounterText extends StatelessWidget {
const CounterText({super.key, required this.listenable});
final ValueListenable<int> listenable;
@override
Widget build(BuildContext context) => ValueListenableBuilder<int>(
valueListenable: listenable,
builder: (_, v, __) => Text('$v'),
);
}
- Extract widget classes instead of helper methods like
Widget _buildHeader(). A class can beconstand has its own rebuild boundary; a method re-runs with its parent. - Use
childparameters.AnimatedBuilder,ValueListenableBuilderandConsumeraccept achildthat is built once and passed through. - Select, do not watch everything. With Provider
context.select, with Riverpodref.watch(p.select(...)). - Stable inputs. Rebuilding an item only matters if its inputs changed; immutable models with
==(viaequatableorfreezed) let Selectors skip updates.
How to check
DevTools > Performance > "Track widget builds", or the Flutter Inspector's rebuild counts in debug.
Pitfall
Do not sprinkle const and then pass changing data; const only compiles if all arguments are constants. Prefer the analyzer fix (dart fix --apply) to add them in bulk.
0