Sub topic 2
Widgets are cheap, immutable descriptions
This chapter assumes you can write basic Dart classes and closures, and that you have built small Flutter apps with StatelessWidget and StatefulWidget. It looks at what a widget is, and what it is not. Most Flutter performance and state bugs come from misreading that.
A widget describes, it does not do
A widget is a configuration object. It says "here is a Padding of 16 pixels around this child". It does not hold pixels, a position, or a size. It also does not remember anything between frames.
The Widget base class is annotated @immutable. Every field on a widget should be final. Its main jobs are small:
- Carry the configuration values you passed to the constructor.
- Carry an optional
key. - Create the long-lived object that manages it, through
createElement().
The long-lived object is the element, which the next chapter covers. A widget is the blueprint, and the element is the building made from it.
import 'package:flutter/widgets.dart';
class LabelChip extends StatelessWidget {
const LabelChip({
super.key,
required this.label,
this.color = const Color(0xFF2196F3),
});
final String label;
final Color color;
@override
Widget build(BuildContext context) {
return DecoratedBox(
decoration: BoxDecoration(color: color),
child: Padding(
padding: const EdgeInsets.all(8),
child: Text(label),
),
);
}
}
void main() => runApp(
const Directionality(
textDirection: TextDirection.ltr,
child: LabelChip(label: 'New'),
),
);LabelChip stores two values, both final, and describes a subtree. It never changes after construction. To show a different label, a parent builds a new LabelChip.
Why throwing widgets away is fine
Flutter expects you to create new widgets constantly. Each call to build returns a fresh set of widget objects, and the previous set is dropped. A typical build method allocates dozens of them per frame.
This is affordable because constructing a widget does very little work:
- It allocates a small Dart object.
- It assigns a few fields.
- It does no layout, no painting, and no native resource allocation.
Dart's generational garbage collector is designed for many short-lived objects. The expensive objects are the render objects, and those are kept alive across rebuilds. The diagram shows the split.
The element keeps a reference to the most recent widget. When a parent rebuilds, the element receives a new widget and applies the differences to its render object. The reuse rule is covered in the reconciliation chapter.
Widgets are values, not identities
Because a widget holds only configuration, two widgets with the same type and the same fields are interchangeable. Flutter does not treat a widget as "the" button. It treats it as "a button with this configuration".
This has a practical consequence. The same widget instance can appear in more than one place in the tree, and each place gets its own element. A const widget is the clearest case. Dart canonicalizes compile-time constants, so equal const expressions give you one shared instance.
import 'package:flutter/widgets.dart';
void main() {
print(identical(const Text('x'), const Text('x'))); // true
print(identical(Text('x'), Text('x'))); // false
}Run this inside a Flutter project, for example from a test, because package:flutter/widgets.dart depends on dart:ui.
Identity matters for performance. When an element updates its child, it first checks whether the new widget is the very same object as the one it already holds. If so, Flutter skips the update for that child and does not rebuild that subtree. A const child therefore costs almost nothing when its parent rebuilds. This is the mechanism behind the advice to "use const constructors".
What not to put in a widget
The immutability rule exists because Flutter may call build at any time and may discard a widget at any time. Anything stored on a widget instance can vanish. The common mistakes follow.
Mutable fields
// Wrong: the widget tries to be a counter.
class BadCounter extends StatelessWidget {
BadCounter({super.key});
int count = 0; // not final; the analyzer reports invalid_immutable_annotation
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () => count++, // changes the field, but nothing rebuilds
child: Text('$count'),
);
}
}There are two problems here. The tap changes the field, but nothing tells Flutter to call build again, so the screen stays stale. Even if something did trigger a rebuild, the parent can replace this widget with a new BadCounter whose count is 0. Changing values belong in a State object, which the element owns and keeps across rebuilds.
Heavy work in constructors or `build`
A widget constructor should only store its arguments. Parsing JSON, sorting a large list, or opening a connection there repeats on every rebuild. Do that work in initState, in a state-management layer, or in a FutureBuilder whose future you created once.
Treating a widget as a handle
You cannot ask a widget for its size, its position, or its children's states. A widget has no link to what is on screen. Those answers come from the element and the render object, reached through BuildContext and RenderBox.
Summary of the widget's role
| Question | Answer for a widget |
|---|---|
| Is it mutable? | No. Fields should be `final`. |
| Does it live across frames? | No. It is recreated on each build. |
| Does it lay out or paint? | No. A render object does that. |
| Where does changing data live? | In a `State` object owned by an element. |
| What makes it cheap to skip? | `const` construction, or an identical instance. |
Exercise
A parent StatefulWidget calls setState every second. Its build returns Column(children: [const Text('Static'), Text(_clock)]). Which of the two Text widgets is skipped during the child update, and why? Does the Column widget object itself get reused?
Show answer
The const Text('Static') is skipped. It is the same canonical instance as in the previous build, so its element sees an identical widget and does no update work for that subtree. Text(_clock) is a new object each build, so its element is updated with the new widget and its render object gets the new string. The Column is created fresh on every build, because it has non-const children and is not a constant. It is cheap to allocate, and its element is reused and updated in place.