
Widgets Are Blueprints, Not Screen Objects: Flutter's Three Trees
- كاتب موثّق
- Flutter 3.x
محتويات المقال
print in the handler shows the field going up, 2, 3, 4, while the screen still says 1. Then the cart total elsewhere on the page updates, and the field itself is back to 1. Flutter isn't broken. The code is changing an object that was never on the screen.
The common misconception
Text('1') is the label on screen, and when your data changes, Flutter updates that object, the way you'd set the text of a UILabel on iOS or a TextView on Android.
StatefulWidget sounds like the widget itself holds state. The half-truth is the structure: the widget tree does describe what's on screen. It just doesn't stay there.
What actually happens
Widgets: immutable blueprints
build() returns brand-new widget objects, and the previous ones are dropped. That's affordable because a widget is a small bundle of constructor arguments, not a view. The same widget object can even be placed in the tree several times.
Elements: the instance at a place in the tree
State of stateful widgets and the render objects underneath. You've already met them, too. The BuildContext passed to build() is, in the docs' words, actually an Element object.
Render objects: layout and paint
Padding creates a RenderPadding, and Text builds a RichText whose render object is a RenderParagraph. Your own StatelessWidget and StatefulWidget classes never create one; they only compose other widgets. That's why the render tree is a subset of the element tree and much smaller than the widget code you write.
What a rebuild really does
setState runs, the framework marks that element dirty. On the next frame:
The element calls build()and gets a fresh set of widgets.For each child, it compares the old and new widget. If their runtimeTypeandkeymatch, which is the rule behindWidget.canUpdate, the existing element is updated with the new widget and keeps itsStateand render object.A render object widget copies its new configuration onto the existing render object, so a changed color or padding is an update in place, not a new object. If the type or key differs, the old element and everything below it is removed, and a new one is created from the new widget. If the new widget is the very same instance as last time, as constwidgets often are, the walk stops there.
import 'package:flutter/material.dart';class QuantityStepper extends StatelessWidget { QuantityStepper({super.key}); int quantity = 1; // warning: must_be_immutable @override Widget build(BuildContext context) { return Row(children: [ Text('$quantity'), IconButton( icon: const Icon(Icons.add), onPressed: () => quantity++, // the field changes, the screen doesn't ), ]); }}import 'package:flutter/material.dart';class QuantityStepper extends StatefulWidget { const QuantityStepper({super.key}); @override State<QuantityStepper> createState() => _QuantityStepperState();}class _QuantityStepperState extends State<QuantityStepper> { int quantity = 1; // lives in the State, which the element keeps @override Widget build(BuildContext context) { return Row(children: [ Text('$quantity'), IconButton( icon: const Icon(Icons.add), onPressed: () => setState(() => quantity++), ), ]); }}quantity++ edits a field on a blueprint. Nothing marks the element dirty, so build() never runs and the Text keeps showing 1. When the parent rebuilds for the cart total, it creates a new QuantityStepper whose field starts at 1 again, and the element switches to that one. The analyzer even warns you: must_be_immutable. In the second version, the number lives in State, which the element owns. Run both in a widget test and you can see it: after three taps and a parent rebuild, the first still showed 1 and the second showed 4, with the same State object as before, even though widget now pointed to a new QuantityStepper instance.
State, the link to its render object | |||
build() | createElement |
How to apply it in your project
Keep every widget field final Treat the must_be_immutablewarning as a bug, not as noise. If a widget needs a value that changes, it doesn't own that value.Put changing data in State, and change it through setState A counter, a selection or a loading flag goes in a Stateobject or in a state-management class above it. Change it insidesetState(or through your state-management tool) so the element is marked dirty and rebuilds.Stop worrying about creating widgets in build() New widget objects on every build are the design, not a leak. Worry about expensive work inside build(), and useconstconstructors where you can so Flutter can skip unchanged subtrees.Debug lost state by looking at types and keys When a Stateresets, check what sits at that position across rebuilds: a different widget class, a conditional that swaps widgets, or a key that changes every time.
Key takeaways
A widget is an immutable blueprint: every build creates new ones and drops the old. The element at each place in the tree persists, holding your Stateand the link to its render object.Render objects do layout and painting, and Flutter updates them in place instead of recreating them. Mutating a widget's field changes nothing on screen; change StatewithsetStateinstead.Same type and key at the same spot keeps the element; anything else replaces it, Stateincluded.
التعليقات (0)