Skip to the workspace
Pebellslearn by building
Widgets  ›  Lesson

Inherited Widgets

Inherited Widgets 12 minAn InheritedWidget makes data available to every widget below it, and widgets that read it with the of(context) pattern rebuild when that data changes.

flutter / Inherited Widgets

Explore each scene at your own pace.

01 · The rule

The rule

Inherited Widgets

Sprout lets the user choose whether water is measured in millilitres or cups. The widget that prints "250 ml" sits five levels down the tree. Passing the unit through every constructor on the way means four widgets carry a value they never use. Flutter has a better route.

The rule

Put data above the tree; any widget below asks for it with of(context).

An InheritedWidget holds data and makes it reachable from every widget beneath it.

class WaterUnits extends InheritedWidget {
  const WaterUnits({super.key, required this.unit, required super.child});

  final String unit; // 'ml' or 'cups'

  static WaterUnits of(BuildContext context) =>
      context.dependOnInheritedWidgetOfExactType<WaterUnits>()!;

  @override
  bool updateShouldNotify(WaterUnits oldWidget) => oldWidget.unit != unit;
}
  • Place it high up: WaterUnits(unit: 'ml', child: SproutHome()).
  • Any widget below reads it: WaterUnits.of(context).unit.
  • Reading it with dependOnInheritedWidgetOfExactType also subscribes that widget: when a new WaterUnits arrives with a different unit, the readers rebuild.
  • updateShouldNotify decides whether a change is worth rebuilding the readers for.

You already use this pattern. Theme.of(context) and MediaQuery.of(context) are built on inherited widgets, which is why a widget that reads the theme updates when the theme changes. Popular state-management packages such as Provider are also built on top of it.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.