Skip to content

avoid_inherited_widget_in_initstate

v0.8.0WarningConfigurableState Management

This rule flags SomeInheritedWidget.of(context) and .maybeOf(context) calls inside a State’s initState method — including Theme.of, MediaQuery.of, Navigator.of, and any custom InheritedWidget.

Those lookups are backed by dependOnInheritedWidgetOfExactType, which is not valid during initState. At that point the element is not fully mounted, so the call either throws outright or silently registers a dependency that never delivers updates. Either way the widget will not rebuild when the theme, media query, or locale changes.

didChangeDependencies exists exactly for this: it runs once immediately after initState, and again every time an inherited dependency changes.

See also: State.initState docs | State.didChangeDependencies docs

class _MyWidgetState extends State<MyWidget> {
late final Color _color;
@override
void initState() {
super.initState();
// Not valid here — throws or never updates
_color = Theme.of(context).primaryColor;
}
}
class _MyWidgetState extends State<MyWidget> {
late Color _color;
@override
void didChangeDependencies() {
super.didChangeDependencies();
// Valid here, and re-runs when the theme changes
_color = Theme.of(context).primaryColor;
}
}

The check descends into closures declared inside initState, because a closure invoked synchronously fails the same way. A lookup inside a closure that deliberately escapes initState — for example one passed to WidgetsBinding.instance.addPostFrameCallback — runs after mounting and is therefore safe, but will still be reported. Suppress those with // ignore: many_lints/avoid_inherited_widget_in_initstate.

This rule is in the recommended preset, so it is on with preset: recommended or preset: opinionated. Add it to preset: core with avoid_inherited_widget_in_initstate: true.

To turn it off:

many_lints.yaml
rules:
avoid_inherited_widget_in_initstate: false

To keep the rule on but skip certain paths, use per-rule exclude.

Projects with a state abstraction that does not extend Flutter’s State can opt that base class into this rule:

analysis_options.yaml
many_lints:
rules:
avoid_inherited_widget_in_initstate:
state_base_classes: [AppState]
Option Type Default Description
state_base_classes list of strings [] Additional non-State base classes whose subclasses should be treated as state classes