尝试在共享首选项中存储令牌但不起作用
trying store token in shared preferences but not working
在 flutter 项目中,我试图在共享首选项中存储令牌和用户 ID,但它不起作用!令牌是字符串,用户 ID 是整数,有人能帮忙吗?
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);
}
shared_preferences插件异步保存数据。因此,如果您想立即获得保存的价值,您应该在 prefs.setString()
之前添加 await
到您的示例:
await prefs.setString('userData', userData);
final extractData =
json.decode(prefs.getString('userData')) as Map<String, dynamic>;
顺便说一下,考虑使用 flutter_secure_storage 来存储访问令牌等敏感数据。不知道你的token是不是保密的,你想想吧
在 flutter 项目中,我试图在共享首选项中存储令牌和用户 ID,但它不起作用!令牌是字符串,用户 ID 是整数,有人能帮忙吗?
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);
}
shared_preferences插件异步保存数据。因此,如果您想立即获得保存的价值,您应该在 prefs.setString()
之前添加 await
到您的示例:
await prefs.setString('userData', userData);
final extractData =
json.decode(prefs.getString('userData')) as Map<String, dynamic>;
顺便说一下,考虑使用 flutter_secure_storage 来存储访问令牌等敏感数据。不知道你的token是不是保密的,你想想吧