Skip to main content

12 - Flutter Internals: Widgets, Elements, Keys and setState

How Flutter reuses or destroys Elements: the type-and-key rule from the source, const, setState, keys and InheritedWidget, with two Dart programs run.

What do you think about this article?

At a Glance

How Flutter reuses or destroys Elements: the type-and-key rule from the source, const, setState, keys and InheritedWidget, with two Dart programs run.

Why state sometimes ends up in the wrong row

You have a list of rows, each with a text field. You delete the first one and the row that used to be the second shows... the text the third had written, or nothing. It is not a Flutter defect, it is the consequence of how the framework decides whether a new configuration can reuse an existing object. Understanding this rule also explains const, setState, keys and InheritedWidget. The rule is just one: Flutter matches the new description to the old object by looking at type and key, and keeps the state in the old object.

A statement of method, before starting. To show the framework's real behaviour I would have to run a widget tree, that is a test or an app, and in this session I did not. Instead I read the Flutter 3.44.2 source code (framework.dart), which is the primary source, and ran two pure Dart programs that reproduce the two rules that matter; the Flutter listings are analysed with flutter analyze and free of errors, but not run. This article completes performance and jank and leans on the examples of BLoC.

Three trees, three jobs

When you write build() you describe the interface with Widget objects: they are immutable configurations, light, created again at every build. The framework turns them into a second tree of Element objects, which are the long-lived ones: each remembers the current widget, its position and, for StatefulWidgets, its State object. A third tree, that of the RenderObjects, computes sizes and positions and paints. The introduction to Flutter's architecture describes this division.

TreeWhat it containsHow long it lives
Widgetimmutable configuration (type, key, parameters)recreated at every build() of the parent
Elementposition in the tree, reference to the current widget, Stateas long as the match with the new widget holds
RenderObjectlayout, hit testing, paintingtied to the Element that owns it

The practical point of the table is in the right-hand column: widgets are cheap because they are thrown away, Elements are the real cost because they are created and destroyed. The goal of every rule that follows is not to destroy an Element unless necessary.

The matching rule: type and key

The code that decides is in the framework source, in Element.updateChild. The condition that allows reusing the Element is in Widget.canUpdate: same runtimeType and same key. The rest is a three-branch decision tree.

The rule, from the Flutter source
// The first lines are copied from packages/flutter/lib/src/widgets/framework.dart (Flutter 3.44.2); not run
  static bool canUpdate(Widget oldWidget, Widget newWidget) {
    return oldWidget.runtimeType == newWidget.runtimeType && oldWidget.key == newWidget.key;
  }

// Summary (not a literal copy) of the branches of Element.updateChild, line 3982 onwards:
if (hasSameSuperclass && child.widget == newWidget) {
  // same instance: no update, no rebuild of the subtree
  newChild = child;
} else if (hasSameSuperclass && Widget.canUpdate(child.widget, newWidget)) {
  child.update(newWidget); // same class and same key: the Element is reused
  newChild = child;
} else {
  deactivateChild(child); // otherwise it is destroyed and recreated
}

Read the branches from the top. If the new widget is the same instance as the old one, the Element does nothing and the subtree is not rebuilt. If it is a different instance but canUpdate is true, the Element stays and receives the new configuration with update, which for a stateless widget also calls rebuild(force: true) (I read this in StatelessElement.update). If there is no match, the Element is discarded together with its state and a new one is created. The second block of the listing is a summary of mine, declared as such in the comment.

const works because identity is the only equality

The first branch compares with ==, and in Widget that operator is marked @nonVirtual: it means identity, two widgets are equal only if they are the same object (lines 365-366 of framework.dart). A const expression in Dart always produces the same instance for the same values. It follows that const Text('Total') inside a build() is, on every call, the same instance, and the first branch skips it. This behaviour does not depend on Flutter, and can be verified in pure Dart:

Two equal const instances are the same object
/// Like Widget, it does not redefine ==: two instances are equal only if they are the same one.
class Label {
  const Label(this.text);
  final String text;
}

void main() {
  const a = Label('Total');
  const b = Label('Total');
  final c = Label('Total'.toString()); // created at runtime: new object
  final d = Label('Total'.toString());

  print('const and const identical : ${identical(a, b)}');
  print('const and runtime         : ${identical(a, c)}');
  print('runtime and runtime       : ${identical(c, d)}');
  print('== between c and d        : ${c == d}');
}

// Output:
// const and const identical : true
// const and runtime         : false
// runtime and runtime       : false
// == between c and d        : false

The first two lines of the output are the mechanism: a and b are the same instance, and one created at runtime with the same content is not. The last line shows that not even == considers them equal, because the class does not redefine it. The advantage of const is therefore narrow and precise: it saves rebuilding that subtree when the parent rebuilds. It does not make a changing widget faster, and it does not replace measuring: the effect is useful where a parent rebuilds often with static children, which you can see with the tools described in integration testing and DevTools.

Keys: simulating the wrong-row case

Back to the list. Without keys, matching is by position and type: after removing the first row, the first Element of the list (which was A's, with its state) receives B's configuration. With a stable key per row, matching is by key. To show it I wrote a simplified model, not the real algorithm (which lives in RenderObjectElement.updateChildren and is more complex): a row has a type, a key and data, an Element has a state, and the update reuses the Element if canUpdate is true.

Model: removing the first row with and without keys
/// Simplified model: a configuration (Widget) is a type, an optional key and a datum.
class W {
  const W(this.type, this.data, {this.key});
  final String type;
  final String data;
  final String? key;
}

/// An "Element": keeps its own state even when the configuration changes.
class E {
  E(this.widget, this.state);
  W widget;
  String state;
}

bool canUpdate(W a, W b) => a.type == b.type && a.key == b.key; // like Widget.canUpdate

/// Updates a list of Elements: without keys by position, with keys by key.
List<E> reconcile(List<E> old, List<W> next) {
  final byKey = {for (final e in old) if (e.widget.key != null) e.widget.key!: e};
  final result = <E>[];
  for (var i = 0; i < next.length; i++) {
    final w = next[i];
    final candidate = w.key != null ? byKey[w.key] : (i < old.length ? old[i] : null);
    if (candidate != null && canUpdate(candidate.widget, w)) {
      candidate.widget = w; // reuse: the configuration changes, the state stays
      result.add(candidate);
    } else {
      result.add(E(w, 'new')); // creation: state lost
    }
  }
  return result;
}

String show(List<E> es) => es.map((e) => '${e.widget.data}[${e.state}]').join(' ');

void main() {
  // Three rows of a list; the user typed something in the second.
  W row(String d, {String? key}) => W('Row', d, key: key);

  for (final withKeys in [false, true]) {
    final before = [row('A', key: withKeys ? 'a' : null), row('B', key: withKeys ? 'b' : null), row('C', key: withKeys ? 'c' : null)];
    var elements = before.map((w) => E(w, 'empty')).toList();
    elements[1].state = 'B text';

    // The first row is removed: B and C remain.
    final after = [row('B', key: withKeys ? 'b' : null), row('C', key: withKeys ? 'c' : null)];
    elements = reconcile(elements, after);
    print('${withKeys ? 'with keys   ' : 'without keys'}: ${show(elements)}');
  }
}

// Output:
// without keys: B[empty] C[B text]
// with keys   : B[B text] C[empty]

The output reproduces the defect in pure form. In the first line the text typed in row B (the one in B's state, which was the Element in second position) ended up next to row C, because it is the second Element and was assigned C's configuration; B received the empty state of the first. In the second line, with keys, the state follows the row. The model is faithful in principle and simplified in details: if you want proof on the real framework, you need a stateful widget in a list and the removal of the first item.

  • ValueKey(id): the normal choice, with a stable domain identifier.
  • ObjectKey(object): when the identity is that of the object and there is no id.
  • UniqueKey(): a new key at every creation, so it destroys state at every rebuild; useful only to force a reset.
  • GlobalKey: lets you reach the State from outside and move an Element between different points of the tree; it is the most expensive.

The practical rule is to use ValueKey on the entries of a dynamic list that have state or animations, and not to add keys elsewhere. The GlobalKey documentation in the source recommends not recreating them on every build, which is why they are kept in the State.

The lifecycle of a State follows the Element

State does not live in the widget, which is thrown away, but in the State object held by the Element. When the Element enters the tree the framework calls initState and then didChangeDependencies; when the parent passes a new configuration it calls didUpdateWidget; when the Element is removed it calls deactivate and finally dispose (lines 5950-6030 of the source). The countdown below uses all three phases.

A countdown: start, new configuration, end (analysed, not run)
import 'dart:async';

import 'package:flutter/material.dart';

class Countdown extends StatefulWidget {
  const Countdown({super.key, required this.seconds});

  final int seconds; // configuration: changes with the parent

  @override
  State<Countdown> createState() => _CountdownState();
}

class _CountdownState extends State<Countdown> {
  late int _left; // state: survives rebuilds
  Timer? _timer;

  @override
  void initState() {
    super.initState(); // only once, when the Element enters the tree
    _left = widget.seconds;
    _timer = Timer.periodic(const Duration(seconds: 1), (_) {
      if (_left > 0) setState(() => _left--);
    });
  }

  @override
  void didUpdateWidget(Countdown old) {
    super.didUpdateWidget(old); // the parent passed a new configuration
    if (old.seconds != widget.seconds) _left = widget.seconds;
  }

  @override
  void dispose() {
    _timer?.cancel(); // without this line the timer keeps running after closing
    super.dispose();
  }

  @override
  Widget build(BuildContext context) => Text('$_left s');
}

_left is state and survives rebuilds; widget.seconds is configuration and changes when the parent rebuilds. That is why didUpdateWidget compares the old value with the new one: if the parent passes a different value, the counter restarts. The _timer?.cancel() line in dispose is the standard example of a resource to release: without it the timer keeps calling setState on an object that is no longer mounted. I did not run the example.

setState rebuilds the whole State, not a leaf

Many articles write that setState rebuilds "only the Text that changes". The source says otherwise: setState runs your function and then calls _element!.markNeedsBuild() (line 1219), which marks that State's Element to be rebuilt; at the next frame the entire build() of that State is called again, and the non-const widgets it returns go through updateChild. What is saved is the work under identical or const children, not the call to your build(). Hence the real advice: move state that changes often into a small widget, so that the build() that reruns is short.

InheritedWidget: rebuilding only those who depend

An InheritedWidget carries a datum downwards. Whoever reads it with dependOnInheritedWidgetOfExactType subscribes and is rebuilt when updateShouldNotify answers true; whoever reads it with getInheritedWidgetOfExactType looks it up without subscribing. Both methods are declared in BuildContext with this difference.

An InheritedWidget with explicit comparison (analysed, not run)
import 'package:flutter/material.dart';

class AppConfig extends InheritedWidget {
  const AppConfig({super.key, required this.apiBaseUrl, required super.child});

  final String apiBaseUrl;

  static AppConfig of(BuildContext context) {
    final config = context.dependOnInheritedWidgetOfExactType<AppConfig>();
    assert(config != null, 'AppConfig not found above this context');
    return config!;
  }

  /// Only descendants that called of() rebuild, and only if this answers true.
  @override
  bool updateShouldNotify(AppConfig old) => apiBaseUrl != old.apiBaseUrl;
}

The value of updateShouldNotify is the lever: here it answers true only if the address changes, so an update of the widget that leaves the same address does not rebuild the subscribed descendants.

What you can do now

You can explain why Flutter reuses or destroys an Element, why const skips work, why the list gets the row wrong without keys, when initState and dispose are called, and why setState is not "local to a leaf". This is the knowledge needed to read smoothness problems in the DevTools Performance tab, and to design the features of the feature-based architecture with state where it is needed and only there. The same three trees also run outside the phone: you see it in Flutter Web with WebAssembly and in Flutter Desktop.

Sources

  • Flutter 3.44.2 source packages/flutter/lib/src/widgets/framework.dart - Widget.canUpdate (line 382), non-virtual operator == (365), Element.updateChild (3982), State.setState and markNeedsBuild (1219), StatefulElement lifecycle (5950-6030), StatelessElement.update (5892); read in ~/flutter, 2026-11-12
  • Flutter architectural overview - Widget, Element and RenderObject trees, accessed 2026-11-12
  • InheritedWidget (Flutter API) - updateShouldNotify and subscription of descendants, accessed 2026-11-12
  • Key (Flutter API) - role of keys in Element matching, accessed 2026-11-12

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects