avoid_build_context_in_providers
v0.8.0 Warning Riverpod State
Flags a BuildContext parameter on a @riverpod provider — either a functional provider or a method of a @riverpod class.
Why use this rule
Section titled “Why use this rule”Providers outlive the widgets that read them. A BuildContext held by a provider can easily refer to a widget that has already been unmounted, and using it then throws dependOnInheritedWidgetOfExactType was called on a defunct widget — or quietly reads stale inherited data. Passing the value you need instead keeps the provider independent of the widget tree, which is also what makes it testable without pumping a widget.
See also: Riverpod families
@riverpodint example(Ref ref, BuildContext context) => 0; // LINT
@riverpodclass Example extends _$Example { @override int build(BuildContext context) => 0; // LINT}// Pass the value read from the context, not the context itself.@riverpodint example(Ref ref, Locale locale) => 0;
// At the call site:ref.watch(exampleProvider(Localizations.localeOf(context)));Ordinary classes and functions are unaffected — only @riverpod declarations are checked:
int helper(BuildContext context) => 0; // no lintConfiguration
Section titled “Configuration”This rule is in the recommended preset, so it is on with
preset: recommended or preset: opinionated. Add it to preset: core with
avoid_build_context_in_providers: true.
To turn it off:
rules: avoid_build_context_in_providers: falseTo keep the rule on but skip certain paths, use per-rule exclude.
Related rules
Section titled “Related rules”avoid_passing_build_context_to_blocs— Prevent passing BuildContext to Bloc or Cubit classes.never_discard_build_context— Don’t discard a BuildContext parameter with a wildcard.use_closest_build_context— Use the inner BuildContext from builder callbacks, not the outer one.avoid_ref_read_inside_build— Subscribe in build; do not read once.