Sub topic 3
The State lifecycle
This chapter assumes you know Dart classes and named constructor parameters, and that you have written a StatelessWidget and a StatefulWidget before. It covers how a State object is created and removed, and how to keep state, rebuilds, and keys under control.
The State lifecycle
A State object is created when Flutter inserts its StatefulWidget into the tree. Flutter calls initState once, before the first build. It calls dispose once when the widget is removed for good. Use initState for setup that happens once, such as creating a controller. Use dispose to release resources, such as calling dispose on that controller.
import 'package:flutter/material.dart';
class NameField extends StatefulWidget {
const NameField({super.key, required this.initialName});
final String initialName;
@override
State<NameField> createState() => _NameFieldState();
}
class _NameFieldState extends State<NameField> {
late final TextEditingController _controller;
@override
void initState() {
super.initState();
_controller = TextEditingController(text: widget.initialName);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return TextField(controller: _controller);
}
}Lifting state up
When two widgets need the same value, move the state to their nearest common parent. The parent passes data down through constructor fields and passes events up through callbacks. The child stays simple and holds no state of its own.
class FavoriteButton extends StatelessWidget {
const FavoriteButton({
super.key,
required this.isFavorite,
required this.onToggle,
});
final bool isFavorite;
final VoidCallback onToggle;
@override
Widget build(BuildContext context) {
return IconButton(
onPressed: onToggle,
icon: Icon(isFavorite ? Icons.favorite : Icons.favorite_border),
);
}
}Keeping rebuilds small
Flutter rebuilds a widget's build method each time its setState runs. Put setState in the smallest widget that needs it. Mark widgets const when their inputs never change, so Flutter can reuse them without rebuilding:
const Text('Settings'); // Flutter reuses this widget instead of rebuilding it.Under the hood: widgets, elements, and render objects
A widget is a cheap, immutable description. Flutter pairs each widget with an element, which lives in the tree and holds the state. Elements decide whether to update, reuse, or replace a widget by comparing its type and key. The render object does the actual layout and painting. Widgets are created often and discarded freely. Elements and render objects persist.
Keys and preserving state
Flutter matches old and new widgets by type and position. When you reorder a list, that matching can attach a state object to the wrong item. A ValueKey built from a stable id tells Flutter which element belongs to which item:
ListView(
children: [
for (final todo in todos)
TodoTile(key: ValueKey(todo.id), todo: todo),
],
)Common mistakes with state
- Creating a controller in
build. Each rebuild makes a new one, so the old one leaks. - Forgetting to call
disposeon controllers, timers, or streams. - Calling
setStateafter the widget has been disposed. Checkmountedbefore calling it from an async callback. - Using
widget.nameinsideinitStateexpecting later changes. UsedidUpdateWidgetto react to new widget values.
> Note: keep state as low in the tree as possible, and lift it only when two widgets truly share it.
Exercise
Why create the TextEditingController in initState instead of in build?
Show answer
build runs on every rebuild. A controller created there would be replaced each time, losing the text the user typed and leaking the old controller. initState runs once, so the controller persists for the life of the State.