【问题标题】:How to save token in the local storage with shared preferences如何使用共享首选项将令牌保存在本地存储中
【发布时间】:2022-10-15 18:59:36
【问题描述】:

我登录时有一个代码,状态码成功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;
    }
  }

这是我的实用程序:

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);
  }
}

但是当我尝试获取数据时 api 无法响应 401 无效,这意味着因为令牌没有保存,所以当我尝试获取用户数据时,响应是 401。

【问题讨论】:

  • 您在哪里(如何)存储 token

标签: flutter dart token


【解决方案1】:
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 {
.....

【讨论】:

猜你喜欢
  • 2021-05-31
  • 2021-08-16
  • 1970-01-01
  • 2013-07-27
  • 1970-01-01
  • 2021-06-02
  • 1970-01-01
  • 1970-01-01
  • 2018-04-15
相关资源
最近更新 更多