4

For accessing providers inside non widget classes I was using Reader function. After updating Riverpod dependency to ^2.0.2 version, It seems, the Reader function is no longer available. What workaround you suggest?

Sould I pass Ref or WidgetRef as an argument to class constructor?

When I pass WidgetRef it doesn't recognize states and methods.

Davoud
  • 2,576
  • 1
  • 32
  • 53

2 Answers2

3

That was a breaking change in Riverpod 2.

You should pass ref as argument, and use ref.read where you used reader before.

Example:

final userTokenProvider = StateProvider<String>((ref) => null);

final repositoryProvider = Provider(Repository.new);

class Repository {
  Repository(this.ref);

  final Ref ref;

  Future<Catalog> fetchCatalog() async {
    String token = ref.read(userTokenProvider);

    final response = await dio.get('/path', queryParameters: {
      'token': token,
    });

    return Catalog.fromJson(response.data);
  }
}

https://riverpod.dev/docs/concepts/combining_providers/#can-i-read-a-provider-without-listening-to-it

samy
  • 91
  • 1
  • 5
0

You can also define a custom `Reader', although this is not recommended. However, it may be handy when you want to gradually migrate to the new version of Riverpod 2.0

typedef Reader = T Function<T>(ProviderBase<T> provider);
Ruble
  • 2,589
  • 3
  • 6
  • 29