Search code examples
flutterdartstate-managementriverpodflutter-riverpod

Future provider doesn't read a riverpod state provider | Flutter


What I'm trying to do is when I log in , it takes the token from the API and update it to the riverpod state provider so the user Future provider sends a get request to the API and get the data from the API and returns it , What my API does is whenever there's a token that means user is authenticated otherwise return a Guest user so everytime I login it returns me as a Guest user because the future provider doesn't read the token state provider

Here's how the token is updated

  Future<LoginResponse?> logintoDjango() async {
...
    if (response.statusCode == 200) {

      String userToken = responseJson['data']['token'];

      await CacheHelper.setString("token", userToken);
      ref.read(userTokenProvider.notifier).update((state) => userToken); //Here how it updates
...
  }

That's where it returns ''

  String getToken() {
    final token = ref.watch(userTokenProvider); 
    if (token.isNotEmpty) {
      return token;
    }
    return CacheHelper.getString("token") ?? ''; 
    
  }

and that's the token provider

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

and that's where it's called

final FutureProvider<UserData> userDataProvider =
    FutureProvider<UserData>((ref) async {
  print("Step1");
...
  final token = ref.read(authHelperProvider).getToken(); //THERE
...
  final response = await client.get(
    url,
    headers: token != '' ? {'Authorization': 'Token ${token}'} : {},
  );
  

  return UserData.fromJson(json.decode(response.body));
});

EDIT:

I tried calling final token = ref.read(authHelperProvider).getToken(); on a different screen in the widget build and It returns the token correctly but it doesn't return it to the future provider

INFO:

CacheHelper is my Shared preferences helper class


Solution

  • Fixed my question after reading the documentation, I've found that It should be ref.watch instead of ref.read and it worked , Thank you so much