Search code examples
flutterriverpod

How can I have access to the ref.read?


class AuthRepository {
  static const storage = FlutterSecureStorage();

  Future<void> signIn(String email, String password) async {
    final Map<String, dynamic> jsonData;
    final String token;
    final url = Uri.parse("http://${dotenv.env['apiUrl']}/auth/");
    final response = await http
        .post(
          url,
          headers: {
            "Content-Type": "application/json",
            "Accept": "application/json"
          },
          body: json.encode({
            "email": email,
            "password": password,
          }),
        )
        .timeout(
          const Duration(seconds: 10),
        );
    if (response.statusCode == 200) {
      jsonData = json.decode(response.body);
      token = jsonData['token'];
      await storage.write(key: "token", value: token);
      ref.read(authTokenProvider.notifier).update((state) => token);    <--- **I want to have access to the ref here**
    } else {
      throw Exception("Error signing in.");
    }
  }
}


final authRepositoryProvider = Provider<AuthRepository>((ref) {
  return AuthRepository();
});

Will adding this work?

AuthRepository{
  Ref ref;
  AuthRepository({
    required this.ref,
  });
}
---
final authRepositoryProvider = Provider<AuthRepository>((ref) {
  return AuthRepository(ref: ref);
});

I am trying to implement a login feature using Riverpod 2.0. After saving the token to the FlutterSecureStorage, I want to change the state of the authTokenProvider which is a StateProvider.


Solution

  • Yes, that would work great :) Another option is to pass ref directly to the function that will use it. For example, like this:

    Future<void> signIn(String email, String password, Ref ref) async { ... }
    

    Also, use a tear-off to shorten the code:

    class AuthRepository{
      final Ref ref;
      AuthRepository(this.ref);
    }
    
    final authRepositoryProvider = Provider<AuthRepository>(AuthRepository.new);