[英]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:以下是可能出错的两种常见方式:
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 属性
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
.您必须将
data
的runtimeType
从_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:这对我有用:
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_annotation
、 json_serializable
、 build_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.