sharon
sharon

Reputation: 403

How to save token in the local storage with shared preferences

I have a code when I do login, and the status code is successful 200 ok:

Future<User?> login(String nim, String password) async {
    String token = await UtilSharedPreferences.getToken();
    SharedPreferences pref = await SharedPreferences.getInstance();
    try {
      var body = {
        'username': nim,
        'password': password,
      };
      var response = await http.post(
        Uri.parse('http://dev.api.app.masoemuniversity.ac.id/v1/login_mhs'),
        headers: {
          'Authorization': 'Bearer $token',
        },
        body: body,
      );
      print(response.statusCode);
      print(response.body);

      if (response.statusCode == 200) {
        return User.fromJson(jsonDecode(response.body));
      } else {
        return null;
      }
    } catch (e) {
      print(e);
      return null;
    }
  }

This my util:

class UtilSharedPreferences {
  static Future<String> getToken() async {
    SharedPreferences _prefs = await SharedPreferences.getInstance();
    return _prefs.getString('access_token') ?? '';
  }

  static Future setToken(String value) async {
    SharedPreferences _prefs = await SharedPreferences.getInstance();
    _prefs.setString('access_token', value);
  }
}

But when I try to get data api can't respond it 401 is invalid this means because token is not saved, so when I try to get user data the response is 401.

Upvotes: 0

Views: 1219

Answers (1)

pmatatias
pmatatias

Reputation: 4404

if (response.statusCode == 200) {
   final User user = User.fromJson(jsonDecode(response.body));
   // 
   await UtilSharedPreferences.setToken(user.data.accessToken); // based on you User model variable
   return user;
} else {
.....

Upvotes: 3

Related Questions