InheritedWidget: Propagate Data Down the Tree
InheritedWidget provides data to any descendant that asks, avoiding prop drilling. It's the basis for Theme.of(context) and other ambient state. The common footgun is calling .of(context) from a context that's an ancestor, not a descendant, of the widget.
WHY IT EXISTS To solve "prop drilling"—the tedious and inefficient process of passing data down through many layers of widgets that don't need the data themselves. InheritedWidget provides a way to share state with an entire subtree without explicit pass-throughs at each level.
THE MENTAL MODEL Think of an InheritedWidget as a scoped service provider. You place it at the top of a widget subtree, and any widget below it can "subscribe" to the data it provides. When the data changes, only the subscribers are notified and rebuilt. It's like an announcement board for a specific section of your app's widget tree.
HOW IT WORKS You create a class that extends InheritedWidget and holds some data. Descendant widgets get a reference to the nearest ancestor of this type using a static of(context) method, which calls context.dependOnInheritedWidgetOfExactType. This call establishes a dependency. When the InheritedWidget is replaced by a new instance (e.g., its parent rebuilds), its updateShouldNotify method is called. If it returns true, Flutter rebuilds all the widgets that established a dependency.
WHEN TO USE IT Use it for "ambient" state that many widgets in a subtree might need, but which would be cumbersome to pass down manually. This is perfect for theme data, user authentication status, locale information, or screen size. It is the low-level primitive that powers many state management libraries like Provider.
WHEN NOT TO USE IT It's not ideal for local widget state that only affects a single widget or its immediate children; StatefulWidget is better for that. For complex, app-wide state, you might prefer a more structured solution like Bloc or Riverpod, which are often built on top of InheritedWidget but provide more features.
ONE CANONICAL EXAMPLE The classic example is Theme.of(context). The Theme widget itself is a StatelessWidget that builds a private _InheritedTheme widget. When you call Theme.of(context), you're actually calling a static method that finds that private InheritedWidget up the tree and returns the ThemeData it holds. This lets any widget in your app access the current theme without you passing the ThemeData object everywhere.
Read the original → api.flutter.dev
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.