D
Flutter CoreIntermediate30 XP6 min read

How does InheritedWidget work and when should you use it?

TL;DR: InheritedWidget propagates data down the widget tree efficiently; descendants call context.dependOnInheritedWidgetOfExactType<T>() to access data and opt into rebuilds when it changes via updateShouldNotify().

Full Answer

InheritedWidget is the foundation of Flutter's dependency injection. It lets you share data with all descendants without threading it through constructors.

When a descendant calls context.dependOnInheritedWidgetOfExactType<T>(), two things happen: (1) it reads the data, and (2) it registers itself as a dependent — Flutter will call build() on it whenever the InheritedWidget notifies.

updateShouldNotify

This method decides whether dependents should rebuild. If you return false, even if the data changed, dependents won't rebuild. Provider, Riverpod, and Theme all use InheritedWidget under the hood.

💡

context.watch<T>() (Provider) is sugar for context.dependOnInheritedWidgetOfExactType<T>(). context.read<T>() uses context.getElementForInheritedWidgetOfExactType<T>() — without registering a rebuild.

Code Examples

dartCustom InheritedWidget from scratch
Output
ThemedButton renders with the color from AppTheme. When AppTheme's color changes, ThemedButton rebuilds automatically.

Interview Tip

💡

Provider is just a wrapper around InheritedWidget + ChangeNotifier. Understanding InheritedWidget directly shows deep knowledge of Flutter's internals.

#inherited-widget#dependency-injection#context#provider