Sub topic 1
How and why widgets rebuild
Prerequisites
You should know basic Dart syntax, StatelessWidget, StatefulWidget, setState, and the build method. You should also be able to run a Flutter app on a device or emulator.
The three parts of a Flutter screen
Flutter describes a screen with three related structures:
- A widget is an immutable description of part of the interface.
- An element is the long-lived object that connects a widget description to its place in the tree.
- A render object performs layout and painting for widgets that need it.
When Flutter calls build, the widget returns a new description. Flutter compares that description with the existing element tree and updates only the parts that need changing. A rebuild therefore does not mean that every pixel is laid out and painted again.
A rebuild is usually cheap. The important question is how much work happens during the rebuild and how large the affected subtree is.
What `setState` does
setState tells Flutter that state used by a State object has changed. Flutter marks that state object's element as dirty, meaning it schedules the element to call build again during a later frame.
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: LikesPage()));
}
class LikesPage extends StatefulWidget {
const LikesPage({super.key});
@override
State<LikesPage> createState() => _LikesPageState();
}
class _LikesPageState extends State<LikesPage> {
int _likes = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Profile')),
body: Column(
children: [
const Text('A large, unchanged header'),
Text('Likes: $_likes'),
ElevatedButton(
onPressed: () => setState(() => _likes++),
child: const Text('Like'),
),
],
),
);
}
}Each tap marks _LikesPageState dirty. Flutter calls the entire build method again, including the header, text, and button. This does not necessarily recreate the corresponding elements. Flutter reuses elements when the widget type and key match.
The rebuild scope is determined by where the state lives. If a page owns a small piece of changing state, the page's whole build method can run when that state changes. Later, you can move the state into a smaller widget to reduce this scope.
Inherited dependencies
An inherited widget provides data to descendants in the widget tree. Examples include Theme, MediaQuery, and Localizations. A descendant registers a dependency when it reads that data through an inherited lookup.
When the inherited widget changes, Flutter marks dependent elements dirty. Those elements rebuild because their input may have changed.
For example, this lookup depends on the inherited MediaQuery data:
final size = MediaQuery.of(context).size;A narrower lookup depends only on the size aspect:
final size = MediaQuery.sizeOf(context);The narrower dependency can avoid rebuilding when unrelated values, such as keyboard insets, change. Choose the narrowest lookup that expresses what the widget needs.
Follow the rebuild path
The relationship can be summarized like this:
A parent rebuild can call the build methods of descendant widgets returned from that parent. However, Flutter can reuse unchanged widget instances and elements. Rebuild logs therefore show activity, not necessarily a performance problem.
When a rebuild is a problem
Investigate when a frequently changing value causes expensive work:
- large lists are rebuilt for every keystroke;
- image processing, sorting, or parsing happens inside
build; - many widgets depend on rapidly changing inherited data;
- animation or scrolling causes frame work above the available budget.
Do not optimize a small, fast build method merely because it runs often. Measure first, then reduce scope where the measurements show avoidable work.
Exercise
What does calling setState do, and why does it not automatically repaint the entire screen?
Show answer
It marks the State object's element dirty so Flutter calls its build method again. Flutter then compares the new widget descriptions and performs layout or painting only for parts that require it.