Widget Tree, BuildContext & Lifecycle

Stateless vs stateful widgets, the widget/element/render trees, BuildContext, keys, and the State lifecycle.

Intermediate · about 8 hours · difficulty 3/5

Learn first: Flutter, Dart Essentials, Layout Systems: Flexbox, Rows, Columns & Stacks

Flutter feels simple until something rebuilds too often or state jumps between list items. Understanding the three trees fixes both.

Three trees

  • Widgets are cheap, immutable descriptions of UI. You create new ones on every build.
  • Elements are the long-lived instances that hold position in the tree and link widgets to state.
  • RenderObjects do layout and painting.

When you call setState, Flutter rebuilds widgets below that point, compares them with the existing elements, and only updates what changed.

Practical rules

  • StatelessWidget for UI that depends only on its inputs; StatefulWidget when it owns changing state.
  • State lifecycle: initState (set up controllers, subscriptions), didUpdateWidget, dispose (always dispose TextEditingController, AnimationController, stream subscriptions).
  • BuildContext is your position in the tree; Theme.of(context) and Navigator.of(context) look upwards from there.
  • Use const constructors to skip rebuilds, and split large build methods into smaller widgets.
  • Keys (ValueKey(item.id)) keep state attached to the right item when lists reorder.

Pitfalls

Using a BuildContext after an await when the widget may be unmounted; check mounted first.

Good enough to move on: you can explain why a checkbox state moves to the wrong row after deleting an item, and fix it with keys.

Key concepts

  • Stateless vs Stateful widgets
  • Widget, Element and RenderObject trees
  • State lifecycle and dispose
  • BuildContext and InheritedWidget
  • Keys
  • const widgets and rebuild cost
  • The mounted check after await

Mini project

Build a reorderable to-do list with per-item checkboxes that keeps state correctly when items are reordered or deleted.

Check yourself

Why is it cheap for Flutter to recreate widgets on every build?

Free resources