D
Widget TreeAdvanced50 XP4 min read

How does Flutter's element reconciliation algorithm work?

TL;DR: Flutter reconciles by checking if the new widget's runtimeType and key match the existing element's. If yes, it updates the element with the new widget config. If no, it deactivates the old element and creates a new one.

Full Answer

When a parent rebuilds, Flutter walks its children in order, comparing each new widget against the existing element at that slot.

  • Same runtimeType + same key → update element.widget, keep RenderObject, keep State
  • Different runtimeType or different key → deactivate old element, create new element and RenderObject
  • No key, same type → positional matching; swapping same-type widgets swaps their configs but NOT their state
  • With key → key is used for matching regardless of position; enables correct state transfer on reorder
🎯

This algorithm is O(n) — one pass through children. React's algorithm is similar but Flutter doesn't need the virtual DOM step because elements already ARE the live instances.

Code Examples

dartReconciliation without keys — state doesn't follow widget
Output
Without keys: state is positional. With ValueKey: state moves with the widget on swap.

Common Mistakes

  • Relying on positional matching for reorderable lists — always add keys
  • Using index as a key in a reorderable list — keys should be stable, unique identities

Interview Tip

💡

Explain the algorithm in terms of 'three questions Flutter asks': same slot? same type? same key? This structured answer impresses interviewers.

#reconciliation#element-tree#diffing#widget-type#keys