read<T> method

  1. @override
T read<T>(
  1. ProviderListenable<T> provider
)
override

Read the state associated with a provider, without listening to that provider.

By calling read instead of watch, this will not cause a provider's state to be recreated when the provider obtained changes.

A typical use-case for this method is when passing it to the created object like so:

final configsProvider = FutureProvider(...);
final myServiceProvider = Provider(MyService.new);

class MyService {
  MyService(this.ref);

  final Ref ref;

  Future<User> fetchUser() {
    // We read the current configurations, but do not care about
    // rebuilding MyService when the configurations changes
    final configs = ref.read(configsProvider.future);

    return dio.get(configs.host);
  }
}

By passing Ref to an object, this allows our object to read other providers. But we do not want to re-create our object if any of the provider obtained changes. We only want to read their current value without doing anything else.

If possible, avoid using read and prefer watch, which is generally safer to use.

Implementation

@override
T read<T>(ProviderListenable<T> provider) {
  _assertNotOutdated();
  assert(!_debugIsRunningSelector, 'Cannot call ref.read inside a selector');
  assert(_debugAssertCanDependOn(provider), '');
  return _container.read(provider);
}