Part 1 · 1 chapters · ~8 min

Widget, Element and Render Trees

Widgets as immutable configuration, elements as persistent instances and the canUpdate rule, State lifecycle, render objects and the box protocol (constraints go down, sizes go up, parent sets position), keys and when they matter, InheritedWidget and how providers work, const widgets, and comparisons with React's reconciliation.

3

Three trees in code

code
// keys keep state attached to the right item when a list reorders or filters
ListView(children: [
  for (final tx in transactions) TransactionTile(key: ValueKey(tx.id), tx: tx),   // not index-based
]);

// the box protocol: constraints down, sizes up, parent positions children
class RenderBadge extends RenderBox with RenderObjectWithChildMixin<RenderBox> {
  @override void performLayout() {
    child!.layout(constraints.loosen(), parentUsesSize: true);       // constraints down
    size = constraints.constrain(child!.size + const Offset(16, 8)); // size up
  }
  @override void paint(PaintingContext ctx, Offset offset) {
    ctx.canvas.drawRRect(RRect.fromRectAndRadius(offset & size, const Radius.circular(8)), Paint()..color = const Color(0xFF6C47FF));
    ctx.paintChild(child!, offset + const Offset(8, 4));
  }
}

const SizedBox(height: 16)   // const widgets are canonicalised: Flutter skips rebuilding them

InheritedWidget lets descendants read a value and rebuild only when it changes; Provider, Riverpod and Theme.of all build on this mechanism.

WIDGET, ELEMENT AND RENDER TREES
cheap descriptions, persistent identity, expensive layout
widget treeimmutable configs, rebuilt oftenelement treeidentity + state, persistsrender treelayout and paint objectsState objectlives on the elementkeysmatch widgets to elements
swipe the figure sideways, or tap expand for full screen
1/4
widgets
A widget is an immutable description ("a Text with this string"). Rebuilding creates new widget objects every frame if needed; they are cheap.
immutable descriptionscheap to recreate