我遇到了从 API 接收的数据的类型错误。为了清楚地模拟这个问题,我在下面提供了一个代码示例:
List<dynamic> dat2 = [{"id1": 'food',},{'id2': "car"}];
var data = {"types": dat2, "clientId": "Id"};
代码:
if (data case {
//how I can cast it to List<Map<String, dynamic>> here without extra code?
"types": List<Map<String, dynamic>> types,
"clientId": String clientId})
{
debugPrint('types:$types, clientId: $clientId');
} else {
debugPrint('Error');
}
错误发生在“types”参数中。我怎样才能在 if 条件下正确地转换它来解决这个问题?
试试这个!
List<dynamic> dat2 = [
{
"id1": 'food',
},
{'id2': "car"}
];
dynamic data = {"types": dat2, "clientId": "Id"};
if (data is Map<String, dynamic> &&
data.containsKey("types") &&
data["types"] is List<dynamic>) {
List<Map<String, dynamic>> types = [];
for (var item in data["types"]) {
if (item is Map<String, dynamic>) {
types.add(Map<String, dynamic>.from(item));
}
}
String clientId = data["clientId"];
debugPrint('types:$types, clientId: $clientId');
} else {
debugPrint('Error');
}