mounted property

bool get mounted

Whether this Ref is still active.

All methods on a provider stop being usable once this becomes false. This happens on purpose, and happens to catch possible race conditions.

The fix is to either use onDispose or mounted to cancel any pending work.

Example using onDispose:

import 'package:dio/dio.dart';
final myProvider = FutureProvider((ref) async {
  final cancelToken = CancelToken();
  // Cancel pending network requests upon dispose
  ref.onDispose(cancelToken.cancel);

  return dio.get(..., cancelToken: cancelToken);
});

Example using mounted:

import 'package:dio/dio.dart';
final myProvider = FutureProvider((ref) async {
  await dio.get(..., cancelToken: cancelToken);
  if (!ref.mounted) throw Exception('cancelled');

  return ...;
});

It is preferable to use onDispose when possible, as this will abort pending work earlier.

In both of the examples above, onDispose will stop the network request while it is in progress. While mounted will let the network request complete, and stop its logic after it is done.

Implementation

bool get mounted => !_element._disposed;