Is there any way to fix this error i am storing in shared preferences as a map but retrieving is a problem is there any way to fix this error. Here is the output of the code
{
"fname": "lsbsb",
"role": "Architect",
"lname": "bxbdbeb",
"work_email": "[email protected] ",
"password": "1234",
"location": "bsbsbs",
"phonenumber": "9181828",
"address": "xbbdbsb",
"zip": "nsbeb",
"country": "zbbdbdb",
"id": 3
}
Encoding part of the code
if (response.statusCode == 200) {
print(response.body);
prefs = await SharedPreferences.getInstance();
String encodedMap = json.encode(response.body);
prefs.setString("UserData", encodedMap);
}
Then the decoding part
getPrefs(BuildContext context) async {
var prefs = await SharedPreferences.getInstance();
final encodedMap = prefs.getString('UserData');
Map<String, dynamic> user = jsonDecode(encodedMap!);}
CodePudding user response:
Hello I tried your code and works well for me. The only difference I used jsonEncode instead json.encode. If persist try debug the response in the decoding part, try final user = jsonDecode(encodedMap!)
and see if the response is a Map or a String
final data = {
"fname": "lsbsb",
"role": "Architect",
"lname": "bxbdbeb",
"work_email": "[email protected] ",
"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);
CodePudding user response:
This is happening because you are trying to encode the response body. There should be json.decode(response.body).
You are trying to encode already string object to string!