DEV3 Technologies home

DEV3 Developer Forum

Does using const widgets really improve Flutter performance, and how do I reduce unnecessary rebuilds?

Flutter helpSolved0 views
dev3 ·

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?

#flutter#performance#const

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

  1. 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'),
      );
}
  1. Extract widget classes instead of helper methods like Widget _buildHeader(). A class can be const and has its own rebuild boundary; a method re-runs with its parent.
  2. Use child parameters. AnimatedBuilder, ValueListenableBuilder and Consumer accept a child that is built once and passed through.
  3. Select, do not watch everything. With Provider context.select, with Riverpod ref.watch(p.select(...)).
  4. Stable inputs. Rebuilding an item only matters if its inputs changed; immutable models with == (via equatable or freezed) 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

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.