Sub topic 1
How and why widgets rebuild
Prerequisites
This chapter assumes you know Dart classes, StatelessWidget and StatefulWidget, and how setState works. You should be able to run a Flutter app on a device or emulator.
How and why widgets rebuild
Flutter describes the UI as a tree of widgets. Each widget's build method returns a description of its part of the screen. A rebuild calls build again and creates new descriptions. Flutter then updates only the parts of the screen that changed.
Two events mark an element as dirty, meaning it needs a rebuild on the next frame:
- Calling
setStateon aStateobject. - A change to an inherited widget that the element depends on, such as
ThemeorMediaQuery.
A large screen becomes slow when one small state change rebuilds hundreds of widgets.
Measure before you optimize
Measure first so you fix the rebuilds that matter. In a debug build, this flag prints the widgets rebuilt in each frame:
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
void main() {
// Debug builds only: prints the widgets that are rebuilt in each frame.
debugPrintRebuildDirtyWidgets = true;
runApp(const Placeholder());
}For timing, run flutter run --profile and open Flutter DevTools. Debug builds add overhead, so their timings are not reliable.
Push state down: limit the scope of setState
Calling setState in a large screen rebuilds everything that build creates. Move the changing state into a small widget so only that widget rebuilds:
class LikeCounter extends StatefulWidget {
const LikeCounter({super.key});
@override
State<LikeCounter> createState() => _LikeCounterState();
}
class _LikeCounterState extends State<LikeCounter> {
int _likes = 0;
@override
Widget build(BuildContext context) {
return Row(
children: [
Text('Likes: $_likes'),
IconButton(
icon: const Icon(Icons.favorite),
onPressed: () => setState(() => _likes++),
),
],
);
}
}Use const to reuse widget instances
A const constructor returns the same instance every time. When a parent rebuilds, Flutter sees the same instance and skips that subtree. Add const to widgets whose values never change:
Column(
children: const [
Text('Title'),
Icon(Icons.star),
],
)Exercise
A StatefulWidget contains a const Icon and a Text whose content changes on each tap. Which part of the screen does the const Icon avoid rebuilding, and why?
Show answer
The const Icon is the same instance on every build, so Flutter skips rebuilding it. Only the Text widget, which receives new data, is rebuilt.