Sub topic 3
Widgets, State Objects, and Rebuilds
Assume you know basic Dart syntax, can build simple Flutter widgets, and understand the difference between StatelessWidget and StatefulWidget. This chapter focuses on the objects Flutter keeps during a rebuild, which explains why hot reload can change the screen without erasing entered data.
Widgets are descriptions
A widget is an immutable description of part of the user interface. Immutable means that its fields do not change after the object is created. For example, a Text widget describes which string to display, and a Padding widget describes how much space to add.
Flutter uses these descriptions to build a widget tree. When something changes, Flutter calls build again and creates a new set of widget descriptions. Creating new widgets does not automatically mean that all application data is lost.
A StatelessWidget stores no mutable screen state. Its build method calculates its result from its fields and inherited values:
class Greeting extends StatelessWidget {
const Greeting({super.key, required this.name});
final String name;
@override
Widget build(BuildContext context) {
return Text('Hello, $name');
}
}The Greeting object cannot change its name. To display another name, Flutter receives a new Greeting object.
Stateful widgets have two parts
A StatefulWidget also describes the interface, but it is paired with a separate State object. The widget holds configuration, while the State object holds mutable data that should survive rebuilds.
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: CounterPage()));
}
class CounterPage extends StatefulWidget {
const CounterPage({super.key});
@override
State<CounterPage> createState() => _CounterPageState();
}
class _CounterPageState extends State<CounterPage> {
int count = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Counter')),
body: Center(child: Text('Count: $count')),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
count++;
});
},
child: const Icon(Icons.add),
),
);
}
}Calling setState tells Flutter that this State object has new data. Flutter schedules its build method again. The method creates a new widget description containing the updated count, while the existing _CounterPageState remains in place.
The element tree connects rebuilds
Flutter internally maintains an element tree between the widget tree and the rendered objects. An element is a mounted location for a widget. It lets Flutter compare a new widget with the widget that previously occupied the same location.
When the new widget has a compatible type and key, Flutter usually updates the existing element instead of creating a new one. For a stateful widget, that element keeps its State object.
This matching explains the behavior of hot reload. Hot reload causes Flutter to reassemble and rebuild parts of the widget tree. Existing state objects normally remain mounted, so values such as count, text-field contents, scroll positions, and selected items can stay unchanged while edited build code appears.
A rebuild is therefore different from a reset. A rebuild recalculates widget descriptions. A reset discards the objects that contain mutable state.
Keys and position affect preservation
Flutter matches children mainly by their type and position. If you reorder stateful children, Flutter may associate an old state object with a different item. A Key gives Flutter a stable identity for a child and helps it preserve the correct state when items move.
Hot reload preserves state only while Flutter can match the new structure to the existing structure. Changing a widget's identity, removing it, or changing the surrounding tree can cause its state to be disposed.
Exercise
Why does changing the text returned by a State object's build method usually keep the current counter value?
Show answer
The rebuild creates new widget descriptions, but Flutter keeps the matching element and its existing State object. The counter field therefore remains in memory.