FlutterIntermediate 2 min read

Flutter InheritedWidget and dependency lookup

Understand how descendants find an ancestor dependency and why updateShouldNotify should reflect meaningful changes.

On this page

InheritedWidget exposes information to descendants through the tree. A dependent context can register interest and rebuild when the inherited widget reports a relevant update. This explains part of how themes and several state-management tools work.

Keep scope deliberate

Place a dependency above the consumers that need it. A wider scope is not automatically better; application-wide state makes ownership and isolation more difficult when only one feature needs the data.

The fragment defines a simple immutable scope. Place it around a child subtree and call ReadingScope.of(context) from inside that subtree.

Worked example

This is a focused code fragment. Place it in the class or file described above; it is not a complete standalone app.

class ReadingScope extends InheritedWidget {
  const ReadingScope({super.key, required this.total, required super.child});
  final int total;

  static ReadingScope of(BuildContext context) {
    final scope = context.dependOnInheritedWidgetOfExactType<ReadingScope>();
    assert(scope != null, 'ReadingScope must be an ancestor');
    return scope!;
  }

  @override
  bool updateShouldNotify(ReadingScope oldWidget) => total != oldWidget.total;
}

Read the result

The scope must already exist above the lookup context. The notification decision compares the data that matters to its dependents. An inherited scope does not itself define how mutable application data is stored or persisted.

Follow dependency registration through the tree

The lookup uses a descendant context to find the nearest matching scope above it. That dependency is why the framework knows which consumers may need a rebuild when the inherited value changes. A plain global variable has no equivalent relationship with the widget tree.

updateShouldNotify compares the meaningful input between two configurations. It should reflect the values consumers depend on, not simply always claim that everything changed.

This scope is a delivery mechanism, not a complete persistence or mutation strategy. Keep its immutable value and the owner that changes that value conceptually separate. BuildContext explains the location rule; shared state explains an explicit mutable model.

Practice and verification

Create one consumer below the scope and another outside it. Explain the outside lookup failure. Then update total through a parent State and observe the dependent rebuild.

How this topic connects

Understand first

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.