Skip to content

use_ref_and_state_synchronously

v0.4.0 Warning Fix Async Safety

This rule warns when ref or state is accessed after an await in a Riverpod Notifier method without first checking ref.mounted. If the notifier gets disposed while the async operation is in progress, accessing ref or state will throw an UnmountedRefException.

Async methods in Notifiers can outlive the notifier itself. When a user navigates away or a provider is disposed mid-await, the notifier is torn down but the async method keeps running. Without a ref.mounted guard, the next ref.read() or state = ... will crash at runtime with an exception that is easy to miss during development but hits users in production.

See also: Riverpod automatic disposal | Flutter mounted check | Dart lint: use_build_context_synchronously

class CounterNotifier extends Notifier<int> {
@override
int build() => 0;
Future<void> incrementDelayed() async {
await Future<void>.delayed(const Duration(seconds: 1));
// Notifier may be disposed by now — this can throw
state = state + 1;
}
}
class CounterNotifier extends Notifier<int> {
@override
int build() => 0;
Future<void> incrementDelayed() async {
await Future<void>.delayed(const Duration(seconds: 1));
if (!ref.mounted) return;
state = state + 1;
}
}

This rule is in the opinionated preset, so it is on with preset: opinionated, or by name:

many_lints.yaml
rules:
use_ref_and_state_synchronously: true

To turn it off again:

many_lints.yaml
rules:
use_ref_and_state_synchronously: false

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