Sub topic 15
InheritedWidget and dependency tracking
This chapter assumes you know the widget, element, and render object split from the earlier chapters. It also assumes you know how setState marks an element dirty, and how BuildContext is the element. Here you will see how Flutter delivers data to deep descendants and rebuilds only the widgets that read it.
The problem InheritedWidget solves
Passing a value through ten constructors to reach a leaf widget is tedious. Rebuilding the whole subtree whenever the value changes is wasteful. InheritedWidget fixes both. A descendant asks for the nearest ancestor of a given type, and Flutter records that the descendant depends on it. When the ancestor changes, only the recorded dependents rebuild.
Theme.of(context), MediaQuery.of(context), and Directionality.of(context) all work this way.
How the lookup works
Every element holds a reference to a table of the InheritedElements above it, keyed by widget runtime type. A child receives its parent's table when it is mounted. An InheritedElement adds itself to the table it passes down. A lookup is therefore a map access, not a walk up the tree.
Two consequences follow:
- The lookup matches the exact type. Asking for
CounterScopewill not find a subclass ofCounterScope. - Only one inherited widget per type is visible from a given point. The nearest one shadows the others.
Each InheritedElement keeps a set of dependent elements. A dependency is created when a descendant calls dependOnInheritedWidgetOfExactType<T>().
| Call | Finds nearest `T` | Registers dependency | Typical use |
|---|---|---|---|
| `dependOnInheritedWidgetOfExactType<T>()` | Yes | Yes | Reading a value in `build` |
| `getInheritedWidgetOfExactType<T>()` | Yes | No | One-time reads, such as in an event handler |
A working example
The widget below exposes an integer. CountLabel reads it, so it depends on the scope. StaticLabel does not read it.
import 'package:flutter/widgets.dart';
void main() => runApp(const ScopeDemo());
class CounterScope extends InheritedWidget {
const CounterScope({super.key, required this.count, required super.child});
final int count;
static CounterScope of(BuildContext context) {
final scope = context.dependOnInheritedWidgetOfExactType<CounterScope>();
assert(scope != null, 'No CounterScope found above this context');
return scope!;
}
@override
bool updateShouldNotify(CounterScope oldWidget) => count != oldWidget.count;
}
class CountLabel extends StatelessWidget {
const CountLabel({super.key});
@override
Widget build(BuildContext context) {
debugPrint('CountLabel build');
return Text('Count: ${CounterScope.of(context).count}');
}
}
class StaticLabel extends StatelessWidget {
const StaticLabel({super.key});
@override
Widget build(BuildContext context) {
debugPrint('StaticLabel build');
return const Text('I do not read the count');
}
}
class ScopeDemo extends StatefulWidget {
const ScopeDemo({super.key});
@override
State<ScopeDemo> createState() => _ScopeDemoState();
}
class _ScopeDemoState extends State<ScopeDemo> {
int _count = 0;
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.ltr,
child: CounterScope(
count: _count,
child: Column(
children: [
GestureDetector(
onTap: () => setState(() => _count++),
child: const Text('increment'),
),
const CountLabel(),
const StaticLabel(),
],
),
),
);
}
}Tap "increment" and the console prints only CountLabel build. ScopeDemo rebuilds, but const StaticLabel() is the identical widget instance as before, so its element is not rebuilt. const CountLabel() is also identical, yet it rebuilds anyway. Its element is a registered dependent, and the notification marks it dirty regardless of widget identity.
What happens on a change
The steps in order:
setStatemarks the owning element dirty. In the next build phase it builds and returns a newCounterScopewidget.- Reconciliation sees the same type and key, so
canUpdateis true and the existingInheritedElementis updated in place with the new widget. - The element calls
updateShouldNotify(oldWidget). If it returnsfalse, nothing else happens. Descendants not otherwise dirty are not rebuilt. - If it returns
true,notifyClientscallsdidChangeDependencieson every dependent element. For aStatefulElementthis also leads toState.didChangeDependencies. - Each dependent is marked dirty and rebuilt once in the same build phase, however many inherited widgets changed.
Why updateShouldNotify matters
If you always return true, every dependent rebuilds on every update of the scope, even when the data is the same. Compare only the values dependents actually read. For mutable objects, comparing by identity misses in-place mutations, which is why such objects are usually paired with a Listenable rather than mutated silently.
Using dependencies in State
A State object can react to changes by overriding didChangeDependencies.
import 'package:flutter/widgets.dart';
class CountLogger extends StatefulWidget {
const CountLogger({super.key, required this.read});
final int Function(BuildContext context) read;
@override
State<CountLogger> createState() => _CountLoggerState();
}
class _CountLoggerState extends State<CountLogger> {
@override
void didChangeDependencies() {
super.didChangeDependencies();
debugPrint('dependency changed, count = ${widget.read(context)}');
}
@override
Widget build(BuildContext context) => const SizedBox.shrink();
}Flutter calls didChangeDependencies once right after initState, then again whenever a registered dependency notifies. It is the right place for work such as subscribing to a stream taken from an inherited object.
Common mistakes
- Looking up from the wrong context. If a
buildmethod creates aCounterScopeand then callsCounterScope.of(context)with its owncontext, the lookup starts at that widget's element, which sits above the scope. It finds nothing. Wrap the reader in aBuilder, or extract it into its own widget, so its context is below the scope. - Reading in a callback with
of. Calling a dependency-registering lookup insideonTapcreates a dependency that is not tied to whatbuilddisplays. UsegetInheritedWidgetOfExactTypeor amaybeOfvariant that does not register. - Expecting rebuilds without a dependency. A descendant that never called the lookup is never notified, even if it displays related data.
- Depending on too much.
MediaQuery.of(context)depends on the entireMediaQueryData, so any change, such as the keyboard opening, rebuilds the caller. Newer APIs such asMediaQuery.sizeOf(context)register a narrower aspect and rebuild less.InheritedModelprovides the same aspect mechanism for your own widgets. - Removing a scope. Moving or reparenting an inherited widget without a
GlobalKeycreates a new element. Its dependents are rebuilt and re-registered.
Performance takeaways
Dependency tracking is cheap. Registration is a set insertion, and lookup is a map read. The cost to watch is the size of each dependent's rebuild. Put the lookup in the smallest widget that needs the value. If a large build method calls of(context) at the top, the entire method reruns on every notification. Splitting the reader into its own widget, as CountLabel does, limits the rebuild to that subtree.
Exercise
In the example, ScopeDemo calls setState and rebuilds, yet StaticLabel build is not printed again while CountLabel build is. Name the two separate mechanisms that explain this.
Show answer
StaticLabel is created with const, so the rebuilt parent hands the element the identical widget instance, and the framework skips rebuilding it. CountLabel is also a const instance, but its element registered as a dependent of CounterScope through dependOnInheritedWidgetOfExactType. When updateShouldNotify returns true, notifyClients marks that element dirty, so it rebuilds regardless of widget identity.
Exercise
A build method returns CounterScope(count: 1, child: Text('${CounterScope.of(context).count}')), using its own context. What goes wrong, and how do you fix it?
Show answer
The context belongs to the element above the new CounterScope, so the lookup does not see it and the assertion fails if no other scope exists higher up. Fix it by wrapping the reader in a Builder, or by moving it into a separate widget, so its context is below the scope.