D
Widget TreeIntermediate30 XP4 min read

How does InheritedWidget work and what is it used for?

TL;DR: InheritedWidget provides a way to efficiently propagate data down the widget tree. Descendant widgets subscribe via context.dependOnInheritedWidgetOfExactType() and rebuild only when the data changes.

Full Answer

InheritedWidget is Flutter's built-in mechanism for passing data down the tree without prop-drilling. It is the foundation that packages like Provider are built on.

When a descendant calls context.dependOnInheritedWidgetOfExactType<MyInherited>(), Flutter registers a dependency. When the InheritedWidget's updateShouldNotify returns true, all dependents are scheduled for rebuild.

๐ŸŽฏ

Provider is essentially a polished wrapper around InheritedWidget + ChangeNotifier. Understanding InheritedWidget helps you understand why Provider.of(context) must be called below the provider in the tree.

Code Examples

dartCustom InheritedWidget
Output
Descendant widgets rebuild when primaryColor changes; no rebuild otherwise

Common Mistakes

  • โœ—Calling dependOnInheritedWidgetOfExactType in initState โ€” context isn't fully set up yet; use didChangeDependencies
  • โœ—Returning true from updateShouldNotify unconditionally โ€” triggers unnecessary rebuilds

Interview Tip

๐Ÿ’ก

Mention that Theme.of(context), MediaQuery.of(context), and Navigator.of(context) all use InheritedWidget under the hood.

#InheritedWidget#context#data-propagation#Provider