Sub topic 1
Why Flutter rebuilds UI from configuration
Flutter does not ask you to edit the screen. You describe what the screen should look like for the current state, and the framework works out how to get there. This chapter explains that model and why it makes the rest of the rendering pipeline work the way it does.
Prerequisites
This chapter assumes you have the following:
- Basic Dart: classes, generics, and closures.
- Experience writing small Flutter apps with
StatelessWidgetandStatefulWidget. - Familiarity with composing
Row,Column,Padding, andText.
You don't need to know anything about elements or render objects yet. Later chapters cover them. Here they appear only as names, so you can see where the story goes next.
UI as a function of state
Many older UI toolkits are imperative. You create a view object, keep a reference to it, and mutate it when something changes. To show a welcome message after login, you find the label, call label.setText(...), then find the sign-in button and hide it. Each state change is a hand-written sequence of mutations. The screen is correct only if every sequence is correct and runs in the right order.
Flutter is declarative. You write one function that takes the current state and returns a description of the whole UI:
UI = build(state)When state changes, you don't patch the old UI. You run the function again and get a new description. The framework compares the new description with what is already on screen and applies the minimum changes.
| Row | Imperative toolkit | Flutter |
|---|---|---|
| You write | Mutations for each transition | One description per state |
| Bugs you get | Stale views, missed updates | Wrong description for a state |
| What persists | The view objects you hold | Framework-owned objects you never hold |
| Cost of a change | Whatever your mutations do | A rebuild, then a diff |
The consequence is that the number of transitions you have to reason about drops to zero. You only reason about states.
A minimal example
The widget below shows one of two messages. Notice what is absent: there is no code that removes the old text or inserts the new one.
import 'package:flutter/widgets.dart';
void main() => runApp(
const Directionality(
textDirection: TextDirection.ltr,
child: Greeter(),
),
);
class Greeter extends StatefulWidget {
const Greeter({super.key});
@override
State<Greeter> createState() => _GreeterState();
}
class _GreeterState extends State<Greeter> {
bool _signedIn = false;
@override
Widget build(BuildContext context) {
debugPrint('build: signedIn = $_signedIn');
return GestureDetector(
onTap: () => setState(() => _signedIn = !_signedIn),
child: Text(_signedIn ? 'Welcome back' : 'Please sign in'),
);
}
}Run it in debug mode and tap the text. Each tap changes _signedIn, calls build again, and prints a line. build returns a brand new GestureDetector and a brand new Text every time. You never keep a reference to the old ones, and you never change them.
What build returns
The objects that build returns are widgets. A widget is an immutable description: its fields are final, and it holds the configuration for one piece of UI, such as a color, a padding value, or a string. It is not the thing drawn on screen.
This is why Flutter can afford to rebuild so often. Creating a Text allocates one small Dart object. It does not create a native view, measure text, or touch the GPU. Dart's generational garbage collector is designed for many short-lived objects, so discarding thousands of widgets per frame is normal.
The expensive objects live elsewhere. Flutter keeps a second tree of long-lived objects, called elements, and a third of render objects that do layout and painting. A rebuild produces new widgets, and the framework then decides, for each position in the tree, whether the existing element and render object can be kept and updated. Most of the time they can.
Rebuilding is therefore not redrawing. A rebuild only re-runs build methods and produces widgets. Whether anything is laid out or painted again depends on whether the comparison found a real difference.
Rules that follow from the model
Because build can run at any time and any number of times, a few rules apply.
- Keep
buildpure. It should read state and return widgets. Don't start network requests, write to storage, or mutate fields inside it. The framework may call it on every frame during an animation, when a parent rebuilds, or when an inherited dependency changes. - Treat widgets as disposable. Don't store a widget you built earlier and expect it to be "the one on screen". A new widget instance with the same fields is equivalent to the old one.
- Change state through
setState. The_signedInfield is ordinary Dart data. Assigning to it does not trigger anything.setStateis what tells the framework to callbuildagain. - Keep long-lived data in
State, not in widget fields. Widget fields are replaced on every rebuild. TheStateobject is the part that survives. A later chapter covers why.
Common mistakes
- Doing work in
buildthat should happen once. Creating aFuture, a controller, or a stream subscription insidebuildrepeats it on every rebuild. Move it toinitStateor a field ofState. - Believing a rebuild is always costly. Rebuilding a small subtree is cheap. The cost problem usually comes from rebuilding a very large subtree for a tiny change, or from heavy computation inside
build. The performance chapter returns to this. - Believing a rebuild is always free. Large
buildmethods that run every animation frame do add up. Splitting widgets and usingconstconstructors limit how much work a change causes. - Comparing widgets by identity to detect change. Two widgets that look identical are different objects. The framework's comparison uses runtime type and key, not object identity of the new widget.
Where this leads
The declarative model creates one question that the rest of the tutorial answers: if every rebuild produces a fresh tree of descriptions, how does Flutter keep a scroll position, a text cursor, or a running animation? The answer is the split into three trees. Widgets describe, elements persist and decide what to reuse, and render objects do the layout and painting. The next chapter looks at widgets themselves and why they are cheap by design.
Exercise
In the Greeter example, you tap the text and the screen updates, but the console prints build only once per tap. A teammate changes onTap to () => _signedIn = !_signedIn (no setState). What happens when you tap, and why?
Show answer
The field _signedIn changes, but no rebuild is scheduled, so build does not run and the screen keeps showing the old text. Nothing prints. The new value appears only when something else triggers a rebuild, such as a hot reload or a parent rebuilding. In the declarative model the screen is only a function of state when build runs again, and setState is what requests that.
Exercise
Why can Flutter rebuild widgets every frame without the app becoming slow, and what must be true of a widget for this to be safe?
Show answer
Widgets are immutable, lightweight descriptions. Creating one allocates a small Dart object and does no layout, painting, or native view work. The costly objects (elements and render objects) are kept and updated when the new widget matches the old one. For this to be safe, build must be pure: it only reads state and returns widgets, with no side effects, because the framework may call it at any time and repeatedly.