FlutterBasic 2 min read

State that lives as long as its widget

Understand StatefulWidget, initState and dispose, and pair resource creation with cleanup.

On this page

A stateful widget separates an immutable configuration from mutable state. The framework can provide a new configuration while keeping the existing state object at the same place in the tree.

Know the lifecycle boundaries

initState runs once for a state object. build can run many times. dispose is the place to release resources owned by that state.

class _SearchPageState extends State<SearchPage> {
  final query = TextEditingController();

  @override
  void initState() {
    super.initState();
    query.addListener(onQueryChanged);
  }

  void onQueryChanged() {
    // Read query.text and update your search state.
  }

  @override
  void dispose() {
    query.removeListener(onQueryChanged);
    query.dispose();
    super.dispose();
  }
}

This is a lifecycle fragment, rather than a complete runnable app.

Avoid side effects in build

Do not start a new timer, network request or subscription every time build runs. A rebuild can happen because of changes outside your widget, and repeated work may be difficult to spot.

After asynchronous work

If asynchronous work completes after a widget leaves the tree, its state may no longer be mounted. Cancel owned work where possible and check mounted before state updates that follow an asynchronous gap.

Pair every resource with its owner

The controller is created once for this State object. Registering its listener in initState means one registration for that lifetime. Removing the listener and disposing the controller in dispose prevents this screen from retaining work after it leaves the tree.

Creating the controller or listener inside build would change the relationship: build may run many times, so you could repeatedly allocate resources or reset editing state. The same reasoning applies to a timer, animation controller or stream subscription. Ask who created it and who is responsible for stopping it.

After await, a callback can resume after the user has navigated away. A mounted check prevents an invalid widget-local update, but cancellation is still preferable for work you own and no longer need. Study the setState-after-dispose investigation and focus timer project to see this lifecycle rule in practical flows.

Try it yourself

Find every controller, timer and subscription in one of your screens. For each resource, identify who owns it and where cleanup happens. If no owner is obvious, simplify the design first.

How this topic connects

Understand first

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.