Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 73 ยท Widgets and the widget tree

BuildContext and InheritedWidget

Understand BuildContext as a position in the widget tree, how Theme.of and MediaQuery.of work, and how InheritedWidget shares data down the tree and triggers rebuilds.

You have already written Theme.of(context) or MediaQuery.of(context).size in a Flutter app, probably without knowing what context really is or how of finds something that no one passed to your widget. Both are explained by one idea: every widget lives at a position in the tree, and Flutter can walk up from that position to find the closest ancestor of a given kind.

This lesson explains BuildContext, shows how InheritedWidget makes data available to a whole subtree (this is how Theme, MediaQuery, Navigator access and Provider all work), and covers the classic errors: using the wrong context and using a context after an await. It builds on the three trees and StatefulWidget and setState.

Real vs stand-in. The Dart code is real Flutter, read-only here. The live examples are JavaScript stand-ins: a small tree where each node knows its parent, and a context object that walks up to find the nearest provider, which is exactly what the framework does with elements.

What is a context?

A position Where a widget sits in the tree.
Look up Search ancestors for what you need.
It is the Element Each widget gets its own context.
1 / 2

BuildContext is a position

build(BuildContext context) receives a handle to the element of that widget. The context lets you ask questions that depend on where you are:

  • "What is the closest Theme above me?" โ†’ Theme.of(context)
  • "How big is the screen?" โ†’ MediaQuery.sizeOf(context)
  • "Which Navigator is closest?" โ†’ Navigator.of(context)
  • "Show a snack bar in the closest Scaffold" โ†’ ScaffoldMessenger.of(context)
  • "What is my size?" โ†’ context.size (only after layout, rarely needed)

Two widgets in different places have different contexts, even if they ask the same question: a Text inside a dark Theme subtree and a Text outside it get different answers to Theme.of(context).

DART
class ThemedLabel extends StatelessWidget {
  const ThemedLabel(this.text, {super.key});
  final String text;

  @override
  Widget build(BuildContext context) {
    final colors = Theme.of(context).colorScheme;
    final width = MediaQuery.sizeOf(context).width;
    return Text(
      text,
      style: TextStyle(
        color: colors.primary,
        fontSize: width < 400 ? 14 : 20,
      ),
    );
  }
}

Nobody passed the theme or the width to ThemedLabel. MaterialApp placed a Theme and a MediaQuery near the top of the tree, and of(context) walked upward until it found them. More on those in Themes, colors and dark mode and Responsive and adaptive layouts.

InheritedWidget

An InheritedWidget is a widget that holds some data and makes it available to every descendant. It has two parts: a static of(context) method you write, and an updateShouldNotify method that decides whether dependents rebuild when the data changes.

DART
class AppSettings extends InheritedWidget {
  const AppSettings({
    super.key,
    required this.username,
    required this.compact,
    required super.child,
  });

  final String username;
  final bool compact;

  static AppSettings of(BuildContext context) {
    final result =
        context.dependOnInheritedWidgetOfExactType<AppSettings>();
    assert(result != null, 'No AppSettings found above this context');
    return result!;
  }

  @override
  bool updateShouldNotify(AppSettings oldWidget) {
    return username != oldWidget.username || compact != oldWidget.compact;
  }
}

Using it:

DART
// Above: provide it
AppSettings(
  username: 'Mina',
  compact: false,
  child: const HomePage(),
)

// Below, at any depth: read it
Text('Hello, ${AppSettings.of(context).username}')

The key call is dependOnInheritedWidgetOfExactType<T>(). It does two things: it finds the nearest ancestor of type T, and it registers the calling element as a dependent. When the inherited widget is rebuilt with new values and updateShouldNotify returns true, every dependent element is marked dirty and rebuilt automatically. Without registering, a widget would read stale data.

There is also getInheritedWidgetOfExactType<T>() (alias for reading without subscribing). Use it when you only need a value once, for example inside an event handler, and do not want rebuilds. This is the idea behind the watch versus read distinction you will meet in State management with Provider.

Stand-in: a context that walks up the tree

JS of(context): nearest provider wins

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Label A is directly under the light app theme. Label B and the deep widget sit under DarkPanel, which overrides the theme for its subtree, so the nearest provider wins. The lookup walks parent links only (cost grows with depth). Flutter makes it cheap: each element stores a table of inherited widgets above it, so lookups are effectively constant time.

Stand-in: dependents rebuild when the value changes

JS updateShouldNotify and dependents

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first update is identical, so updateShouldNotify says no and nobody rebuilds. The two real changes rebuild the subscribed watcher (1 initial build + 2 rebuilds = 3) but never the reader, which did not subscribe.

Context pitfalls

1. Using the context of the widget that creates the provider. of(context) searches above the context. If a widget builds a Theme or Scaffold and then uses its own context to look for it, the lookup fails, because its own context is above the new widget.

DART
// Broken: this context is ABOVE the Scaffold created in the same build.
Widget build(BuildContext context) {
  return Scaffold(
    body: TextButton(
      onPressed: () => Scaffold.of(context).openDrawer(), // error
      child: const Text('Menu'),
    ),
  );
}

// Fixed: Builder creates a new context below the Scaffold.
Widget build(BuildContext context) {
  return Scaffold(
    body: Builder(
      builder: (innerContext) => TextButton(
        onPressed: () => Scaffold.of(innerContext).openDrawer(),
        child: const Text('Menu'),
      ),
    ),
  );
}

Extracting a new widget class has the same effect as Builder, and is usually cleaner.

2. Using BuildContext across an async gap. After an await, the widget might have been removed. Check context.mounted before using it:

DART
Future<void> _save() async {
  await repository.save(_draft);
  if (!context.mounted) return;
  ScaffoldMessenger.of(context).showSnackBar(
    const SnackBar(content: Text('Saved')),
  );
}

The linter rule use_build_context_synchronously warns about this (Futures, async/await and Streams explains why awaits create gaps).

3. Calling of(context) in initState. The dependency system is not ready yet. Use didChangeDependencies, or read it in build.

4. Subscribing to too much. MediaQuery.of(context) makes the widget rebuild when any media property changes, such as the keyboard opening. Prefer the specific forms MediaQuery.sizeOf(context) or MediaQuery.paddingOf(context), which subscribe only to what you read.

Why this matters for state management

Packages like Provider and Riverpod (State management with Provider, Riverpod) are built on this mechanism: they place an inherited widget (or similar lookup) near the top and let descendants find shared objects and subscribe to changes. Understanding InheritedWidget means understanding the foundation of most state management in Flutter. You rarely write one by hand; you use Theme, MediaQuery and a state management package. Still, knowing what happens under of(context) makes error messages like "No MediaQuery widget found" easy to fix.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the BuildContext passed to build represent?

    A BuildContext is the element, which knows where it sits in the tree and can search its ancestors.
  2. 2. What does context.dependOnInheritedWidgetOfExactType<T>() do besides finding the nearest T?

    It subscribes the calling element. When the inherited widget updates and updateShouldNotify returns true, dependents rebuild.
  3. 3. Scaffold.of(context) fails when called inside the same build method that creates the Scaffold. Why?

    The lookup starts from your own context and goes up. A Builder or a new widget class gives you a context below the Scaffold.
  4. 4. What should you do before using a context after an await?

    The widget may have been disposed during the await. context.mounted tells you whether it is still safe to use.
  5. 5. What does updateShouldNotify control?

    Return true when the data changed in a way dependents care about; return false to skip pointless rebuilds.

Summary

  • BuildContext is the element's handle to its position in the tree; of(context) walks up to the nearest ancestor of the requested type.
  • InheritedWidget shares data with a subtree; dependOnInheritedWidgetOfExactType subscribes the caller and updateShouldNotify decides who rebuilds.
  • Theme, MediaQuery and state management packages all use this mechanism; prefer narrow lookups like MediaQuery.sizeOf.
  • Use a Builder or a separate widget class to get a context below a widget you just created.
  • Check context.mounted after any await, and never look up dependencies in initState.

Next: Constraints Go Down, Sizes Go Up