Search code examples
apiflutterdartsharedpreferencestoken

trying store token in shared preferences but not working


in flutter project i'm trying to store token and user id in shared preferences but it does not work!token is string and user id is integer can anyone help?

final responseData = json.decode(response.body);
      if (responseData['login_token'] != null) {
        _token = responseData['login_token'];
        _userID = int.parse(responseData['account_id']);
      }
      final prefs = await SharedPreferences.getInstance();
      final userData = json.encode({'userId': _userID, 'token': _token});
      prefs.setString('userData', userData);

      final extractData =
          json.decode(prefs.getString('userData')) as Map<String, dynamic>;

      if (extractData['userId']) {
        _userID = int.parse(extractData['userId']);
        print("id2" + _userID.toString());
        _token = extractData['token'];
        print('token is:' + _token);
      }

Solution

  • shared_preferences plugin saves data asynchronously. So you should add await before prefs.setString() to your example if you want to immedietly get saved value:

          await prefs.setString('userData', userData);
          final extractData =
              json.decode(prefs.getString('userData')) as Map<String, dynamic>;
    

    By the way, consider to use flutter_secure_storage to store sensitive data like access tokens. I'm not sure if your token is secret or not, just think about it.