是否有任何方法可以修复此错误,我将其存储在共享首选项中作为映射,但检索是一个问题,是否有任何方法可以修复此错误。这是代码的输出
{
"fname": "lsbsb",
"role": "Architect",
"lname": "bxbdbeb",
"work_email": "lemu12@gmail.com ",
"password": "1234",
"location": "bsbsbs",
"phonenumber": "9181828",
"address": "xbbdbsb",
"zip": "nsbeb",
"country": "zbbdbdb",
"id": 3
}
编码部分代码
if (response.statusCode == 200) {
print(response.body);
prefs = await SharedPreferences.getInstance();
String encodedMap = json.encode(response.body);
prefs.setString("UserData", encodedMap);
}
然后解码部分
getPrefs(BuildContext context) async {
var prefs = await SharedPreferences.getInstance();
final encodedMap = prefs.getString('UserData');
Map<String, dynamic> user = jsonDecode(encodedMap!);}
你好,我尝试了你的代码,对我来说效果很好。唯一的区别是我使用jsonEncode而不是json. codede。如果坚持尝试调试解码部分的响应,请尝试最终用户=jsonDecode(codedMap!)
并查看响应是Map还是String
final data = {
"fname": "lsbsb",
"role": "Architect",
"lname": "bxbdbeb",
"work_email": "lemu12@gmail.com ",
"password": "1234",
"location": "bsbsbs",
"phonenumber": "9181828",
"address": "xbbdbsb",
"zip": "nsbeb",
"country": "zbbdbdb",
"id": 3
};
final prefs = await SharedPreferences.getInstance();
String encodedMap = jsonEncode(data);
await prefs.setString("UserData", encodedMap);
// Get response
final dataEncoded = prefs.getString('UserData');
Map<String, dynamic> user = jsonDecode(dataEncoded ?? '');
print(user);
发生这种情况是因为您正在尝试对响应正文进行编码。应该有json. decode(response.body)。
您正在尝试将已经字符串对象编码为字符串!