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
dependOnInheritedWidgetOfExactTypealso subscribes that widget: when a newWaterUnitsarrives with a different unit, the readers rebuild. updateShouldNotifydecides 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.