Sparround

BuildContext and InheritedWidget

A `BuildContext` is the widget's position in the element tree — not the widget itself. That is what makes "looking upward" possible: Theme.of(context), Navigator.of(context) and MediaQuery.of(context) all do the same thing — walk up the tree looking for a widget of a given type.

Underneath that lookup sits `InheritedWidget`, Flutter's built-in mechanism for passing data down the tree. It gives you two things:

  • O(1) access — a direct lookup rather than a walk
  • Automatic subscription — widgets that read it rebuild when it changes

In practice you rarely write an InheritedWidget by hand — Provider, Riverpod and InheritedNotifier are all built on top of it. But knowing how it works is an interview expectation, because it is the foundation every state-management package rests on.

The most common practical problem is the wrong context: if the context you pass to showDialog or Navigator.of(context) sits above the part of the tree you need, you get a "No Navigator/Scaffold found" error. The usual fix is a Builder widget to obtain a context at the right level.

Interview tip. This is the answer to "how does Provider work under the hood?": InheritedWidget. Show the mechanism — of(context) calls dependOnInheritedWidgetOfExactType, which both finds the widget and registers the current element as depending on it, so only dependent elements rebuild when the data changes. That explanation moves you from "uses the package" to "knows what it does".

📚 Sources and documentation