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
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.