简体   繁体   English

未处理的异常:InternalLinkedHashMap<string, dynamic> ' 不是类型 'List 的子类型<dynamic></dynamic></string,>

[英]Unhandled Exception: InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>

I am trying to get the JSON response from the server and output it to the console.我正在尝试从服务器获取 JSON 响应并将其发送到控制台 output。

Future<String> login() async {
    var response = await http.get(
        Uri.encodeFull("https://etrans.herokuapp.com/test/2"),
        headers: {"Accept": "application/json"});

    this.setState(() {
      data = json.decode(response.body);
    });


    print(data[0].name);
    return "Success!";
  }

Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List未处理的异常:类型“_InternalLinkedHashMap<String, dynamic>”不是类型“List”的子类型

What could be the reason?可能是什么原因?

Here are 2 common ways this could go wrong:以下是可能出错的两种常见方式:

  1. If your response is a json array like如果您的响应是一个 json 数组,例如

    [ { key1: value1, key2: value2, key3: value3, }, { key1: value1, key2: value2, key3: value3, }, ..... ]

    Then, we use data[0]["name"] , not data[0].name Unless we cast to an object that has the name property, we cannot use data[0].name然后,我们使用data[0]["name"] ,而不是data[0].name除非我们强制转换为具有 name 属性的对象,否则我们不能使用data[0].name

    We cast like this data = json.decode(response.body).cast<ObjectName>();我们像这样data = json.decode(response.body).cast<ObjectName>();

    ObjectName can be whatever object you want (Inbuilt or Custom). ObjectName可以是您想要的任何对象(内置或自定义)。 But make sure it has the name property但请确保它具有 name 属性

  2. If your response is a JSON object like如果您的响应是 JSON 对象,例如

    { dataKey: [ { key1: value1, key2: value2, key3: value3, } ] }

    Then json.decode will return a Map , not a List然后json.decode将返回一个Map ,而不是一个List

     Map<String, dynamic> map = json.decode(response.body); List<dynamic> data = map["dataKey"]; print(data[0]["name"]);

您可以使用new Map<String, dynamic>.from(snapshot.value);

Easiest way (one dimensional):最简单的方法(一维):

Map<String, dynamic> data = new Map<String, dynamic>.from(json.decode(response.body));

print(data['name']);

As doesn't change the type, it's just an assertion.由于不会改变类型,它只是一个断言。

You need to use:您需要使用:

map['eventType'].cast<String, dynamic>() or map['eventType'].cast<String, dynamic>()

Map<String, dynamic>.from(map['eventType'])

You can also solved by this way:也可以这样解决:

Map<String, dynamic> myMap = Map<String, dynamic>.from(/*Your Source*/ );

You are trying to case an Instance of InternalLinkedHashMap which is not possible.您正在尝试处理不可能的InternalLinkedHashMap实例。

You should Serialize and deserialize it back to Map<String, dynamic> .您应该将其序列化序列化回Map<String, dynamic>

InternalLinkedHashMap<String, dynamic> invalidMap;

final validMap =
        json.decode(json.encode(invalidMap)) as Map<String, dynamic>;

You have to convert the runtimeType of data from _InternalLinkedHashMap to an actual List .您必须将dataruntimeType_InternalLinkedHashMap转换为实际的List

One way is to use the List.from .一种方法是使用List.from

final _data = List<dynamic>.from(
  data.map<dynamic>(
    (dynamic item) => item,
  ),
);

If you need work with generic fields has a workaround:如果您需要使用通用字段,有一个解决方法:

class DicData
{
  int tot;
  List<Map<String, dynamic>> fields;

  DicData({
    this.tot,
    this.fields
  });

 factory DicData.fromJson(Map<String, dynamic> parsedJson) {
    return DicData(
        tot: parsedJson['tot'],
        //The magic....
        fields : parsedJson["fields"] = (parsedJson['fields'] as List)
            ?.map((e) => e == null ? null : Map<String, dynamic>.from(e))
            ?.toList()
    );
  }

}

You can get this error if you are using retrofit.dart and declare the wrong return type for your annotated methods:如果您使用retrofit.dart并为您的注释方法声明错误的返回类型,您可能会收到此错误:

@GET("/search")
Future<List<SearchResults>> getResults(); 
// wrong! search results contains a List but the actual type returned by that endpoint is SearchResults 

vs对比

@GET("/search")
Future<SearchResults> getResults(); 
// correct for this endpoint - SearchResults is a composite with field for the list of the actual results

This worked for me:这对我有用:

  1. Create a List Data创建列表数据
  2. Use Map to decode the JSON file使用 Map 解码 JSON 文件
  3. Use the List object Data to fetch the name of the JSON files使用 List 对象 Data 获取 JSON 文件的名称
  4. With the help of index and the list object I have printed the items dynamically from the JSON file在索引和列表对象的帮助下,我从 JSON 文件中动态打印了项目
setState(){

    Map<String, dynamic> map = json.decode(response.body);
    Data  = map["name"];
}

// for printing
Data[index]['name1'].toString(),

如果您使用 Firebase Cloud,请确保您没有尝试添加具有相同 DocumentID 的多个数据;

firestore.collection('user').document(UNIQUEID).setData(educandos[0].toJson()).

Seems like this error could pop up depending on various developer faults.似乎此错误可能会根据各种开发人员错误弹出。
In my case, I was using an EasyLocalization key but without defining it under asset/lang/en_US.json file.就我而言,我使用的是EasyLocalization键,但没有在asset/lang/en_US.json文件下定义它。

To convert from _InternalLinkedHashMap<String, dynamic> to Map<String, double> I used从 _InternalLinkedHashMap<String, dynamic> 转换为 Map<String, double> 我使用

Map<String,double>.from(json['rates']) 

I had the same error using json_annotation , json_serializable , build_runner .我在使用json_annotationjson_serializablebuild_runner时遇到了同样的错误。 It occurs when calling the ClassName.fromJson() method for a class that had a class property (example: class User has a property class Address).当为具有类属性的类调用ClassName.fromJson()方法时会发生这种情况(例如:类 User 具有属性类 Address)。

As a solution, I modified the generated *.g.dart files of each class, by changing Map<String, dynamic>) to Map<dynamic, dynamic>) in everywhere there is a deep conversion inside the method _$*FromJson作为一种解决方案,我修改了每个类的生成*.g.dart文件,通过将Map<String, dynamic>)更改为Map<dynamic, dynamic>)在方法_$*FromJson内部存在深度转换的任何地方

The only problem is that you have to change it again every time you regenerate your files.唯一的问题是每次重新生成文件时都必须再次更改它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 未处理的异常:类型 '_InternalLinkedHashMap<string, dynamic> ' 不是类型 'String' 的子类型</string,> - Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String' 未处理的异常:类型 '_InternalLinkedHashMap<string, dynamic> ' 不是类型 'List 的子类型<dynamic> ' 在类型转换中?</dynamic></string,> - Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>' in type cast? 从 api 错误中获取 Json 未处理的异常:类型 '_InternalLinkedHashMap<string, dynamic> ' 不是类型 'List 的子类型<dynamic> '</dynamic></string,> - Fetching Json from api error Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>' Flutter dart json 未处理的异常:InternalLinkedHashMap<string, dynamic> ' 不是类型 'List 的子类型<dynamic></dynamic></string,> - Flutter dart json Unhandled Exception: InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic> 在 dart 中解析对象(未处理的异常:类型 &#39;_InternalLinkedHashMap<dynamic, dynamic> &#39; 不是类型 &#39;Map 的子类型<String, dynamic> &#39;) - Parsing object in dart (Unhandled Exception: type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, dynamic>') 未处理的异常:类型 '_InternalLinkedHashMap<string, dynamic> ' 不是 'HashMap 类型的子类型<string, dynamic> ' Dart</string,></string,> - Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'HashMap<String, dynamic>' Dart E/Flutter 未处理异常:类型 _InternalLinkedHashMap<dynamic, dynamic> ' 不是类型 'Map 的子类型<string, string> ?</string,></dynamic,> - E/Flutter Unhandled Exception: type _InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, String>? 未处理的异常:类型 '_InternalLinkedHashMap<dynamic, dynamic> ' 不是类型 'Map 的子类型<datetime, list<account> &gt;' 类型转换</datetime,></dynamic,> - Unhandled Exception: type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<DateTime, List<Account>>' in type cast 嵌套对象 - 未处理的异常:类型 &#39;_InternalLinkedHashMap<String, dynamic> &#39; 不是 &#39;Iterable 类型的子类型<dynamic> - Nested Object - Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable<dynamic> Dart 未处理的异常:类型 &#39;_InternalLinkedHashMap<String, dynamic> &#39; 不是 &#39;Iterable 类型的子类型<dynamic> - Dart Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable<dynamic>
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM