提问者:小点点

未处理的异常:类型'String'不是类型'Map<String,动态>flutter的子类型


是否有任何方法可以修复此错误,我将其存储在共享首选项中作为映射,但检索是一个问题,是否有任何方法可以修复此错误。这是代码的输出

{
    "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!);}


共2个答案

匿名用户

你好,我尝试了你的代码,对我来说效果很好。唯一的区别是我使用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)。

您正在尝试将已经字符串对象编码为字符串!