I have a Dio service that is returning some json:
final response = await di<Api>().dio.get('Measurement');
final List<InspectionResponse> ret = response.data.map((e) => InspectionResponse.fromJson(e)).toList();
My json look like this:
[
{
id: a7fa071d-d518-4c65-8dd1-4c0a04939f45,
blobName: d19e5f92-f326-437f-8e72-72268def65ec_42a4c288-ee16-4332-91eb-d961201c086d,
description: null,
measurementType: 1,
state: 3,
score: 0.32693514227867126,
tagName: Grit-Fine,
createdAt: 2022-09-02T12: 43: 48.582Z
},
{
id: a7fa071d-d518-4c65-8dd1-4c0a04939f46,
blobName: d19e5f92-f326-437f-8e72-72268def65ec_42a4c288-ee16-4332-91eb-d961201c086d,
description: null,
measurementType: 1,
state: 3,
score: 0.32693514227867126,
tagName: Grit-Fine,
createdAt: 2022-09-02T12: 43: 48.582Z
}
]
My model is this:
@JsonSerializable()
class InspectionResponse {
final String id;
final String blobName;
final int state;
final int measurementType;
final double score;
final String tagName;
final DateTime createdAt;
final String? description;
InspectionResponse(this.id, this.blobName, this.state, this.measurementType,
this.score, this.tagName, this.createdAt, this.description);
factory InspectionResponse.fromJson(Map<String, dynamic> json) =>
_$InspectionResponseFromJson(json);
Map<String, dynamic> toJson() => _$InspectionResponseToJson(this);
}
And the genetated _$InspectionResponseFromJson:
InspectionResponse _$InspectionResponseFromJson(Map<String, dynamic> json) =>
InspectionResponse(
json['id'] as String,
json['blobName'] as String,
json['state'] as int,
json['measurementType'] as int,
(json['score'] as num).toDouble(),
json['tagName'] as String,
DateTime.parse(json['createdAt'] as String),
json['description'] as String?,
);
The line:
final List<InspectionResponse> ret = response.data.map((e) => InspectionResponse.fromJson(e)).toList();
Give me this error:
Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<InspectionResponse>'
But I do not understand this? The .map function convert the List<dynamic> to List<InspectionResponse> I would think, as the InspectionResponse.fromJson(e) returns a InspectionResponse, right? So what am I missing here?
CodePudding user response:
This should work:
final List<InspectionResponse> ret = response.data.map<InspectionResponse>((e) => InspectionResponse.fromJson(e)).toList();