如何使用SharedPreferences设置和获取数据



以前我使用SharedPreferences来获取用户名。没关系。

来自API响应

"status": 200,
"message": "Login Successfully",
"result": {
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9mYzBhLTIwMi0xODctMy01Lm5ncm9rLmlvXC9hcGlcL2F1dGhcL2xvZ2luIiwiaWF0IjoxNjM5OTAxMDQ0LCJleHAiOjE2Mzk5ODc0NDQsIm5iZiI6MTYzOTkwMTA0NCwianRpIjoidndLWHlOYlJmTXdzMlFZbCIsInN1YiI6MiwicHJ2IjoiODdlMGFmMWVmOWZkMTU4MTJmZGVjOTcxNTNhMTRlMGIwNDc1NDZhYSJ9.Tr_CTZeKX6M2pycRal7CGeQ0i3FA3Fco0Xm5dwtWwDA",
"user": {
"id": 2,
"name": "hani",

设置并获取

if (res.statusCode == 200) {
setState(() {
message = "Login Success";
});
print(res.body);
SharedPreferences localStorage = await SharedPreferences.getInstance();
localStorage.setString('user', json.encode(body['result']['user']));
String name;
_loadUserData() async {
SharedPreferences localStorage = await SharedPreferences.getInstance();
var user = jsonDecode(localStorage.getString('user'));
if (user != null) {
setState(() {
name = user['name'];
});
}
}

但是如果我想从这个API响应中获取id,我应该写什么?使用SharedPreferences设置并获取该id。

或者还有其他方法可以获得身份证?

"status": "success",
"result": [
{
"id": 1,
"exercise_name": "Reading Set 1",
"exercise_type_id": 1,
"show": 1,
"finalized": 1,
"created_at": "2021-12-17T07:13:50.000000Z",
"updated_at": "2021-12-17T20:47:57.000000Z",
"total": 0
},
{
"id": 3,
"exercise_name": "Reading Set 2",
"exercise_type_id": 1,
"show": 1,
"finalized": 1,
"created_at": "2021-12-17T20:34:50.000000Z",
"updated_at": "2021-12-17T20:46:15.000000Z",
"total": 0
}
]

对不起,我对编码和颤动很陌生。希望有人能帮助

在第一个响应中,resultJSONObject,但在第二个响应中是JSONArray

if (res.statusCode == 200) {
//do what ever you want
final data = jsonDecode(response.body) as Map<String, dynamic>;
for (var exercise in data['result']) {
//Now you can access each item
if(exercise['exercise_name']== 'Reading Set 1'){
//Store ID in SharedPrefrence
}
}
}

相关内容

  • 没有找到相关文章

最新更新