How to save value correctly in Sharedpreferences? - Flutter

Asked

Viewed 197 times

-1

Hello, everybody!

Where am I going wrong?

I have login with google to pick up the token and send to graphgl. This token is saved - at least that’s what it should be - in sharedpreferences, but it’s not saving. I have the following action (mobx).

@action
Future loginWithGoogle() async {
 user = await _authRepository.getGoogleLogin();
 final idToken = await user.getIdToken();
 print('Bearer ${idToken.token}');
 sharedPreferenceService.setToken('Bearer ${idToken.token}');
}

Services Shared.

class SharedPreferenceService {
  SharedPreferences _prefs;

  Future<bool> getSharedPreferencesInstance() async {
    _prefs = await SharedPreferences.getInstance().catchError((e) {
      print("shared prefrences error : $e");
      return false;
    });
    return true;
  }

  Future setToken(String token) async {
    await _prefs.setString('token', token);
  }

  Future clearToken() async {
    await _prefs.clear();
  }

  Future<String> get token async => _prefs.getString('token');
}

SharedPreferenceService sharedPreferenceService = SharedPreferenceService();

Action for login in view.

@action
  Future loginWithGoogle() async {
    try {
      loading = true;
      await auth.loginWithGoogle();
      Modular.to.pushReplacementNamed('/index');
    } catch (e) {
      loading = false;
    }
  }

Login happens normal but error when going to index, stating that received null getString("token").

I/flutter ( 3198): ClientException: Unhandled Failure NoSuchMethodError: The method 'getString' was called on null.
I/flutter ( 3198): Receiver: null
I/flutter ( 3198): Tried calling: getString("token")

This string token is not being saved.

1 answer

1

Correcting...

Returns empty without saving anything yet.

Future get token async => (await _prefs.getString('token')) ?? '';
  • Fixed the action &#xA;@action&#xA; Future loginWithGoogle() async {&#xA; user = await _authRepository.getGoogleLogin();&#xA; final idToken = await user.getIdToken();&#xA; print('Bearer ${idToken.token}');&#xA; bool value = await sharedPreferenceService.getSharedPreferencesInstance();&#xA; if (value == true) {&#xA; sharedPreferenceService.setToken('Bearer ${idToken.token}');&#xA; }&#xA; }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.