Reputation: 57
When I'm trying to get data from API flutter to give this error.
Exception has occurred._TypeError(type '(dynamic)=>Patient' is not a subtype of type '(String, dynamic)= MapEntry<dynamic, dynamic>' of 'transform')
JSON data
{
"pageIndex": 0,
"pageSize": 0,
"count": 0,
"data": [
[
{
"id": 0,
"hospitalId": 0,
"hospitalName": "string",
"firstName": "string",
"lastName": "string",
"doB": "2022-03-24T05:53:54.906Z",
"mobileNumber": "string",
"gender": "string",
"maritalStatus": "string",
"primaryMember": true,
"membershipRegistrationNumber": "string",
"address": "string",
"divisionId": 0,
"division": "string",
"upazilaId": 0,
"upazila": "string",
"districtId": 0,
"district": "string",
"nid": "string",
"bloodGroup": "string",
"branchId": 0,
"branchName": "string",
"isActive": true,
"note": "string",
"covidvaccine": "string",
"vaccineBrand": "string",
"vaccineDose": "string",
"createdOn": "2022-03-24T05:53:54.906Z",
"createdBy": "string",
"updatedOn": "2022-03-24T05:53:54.906Z",
"updatedBy": "string",
"userName": "string"
}
]
]
}
Dart Class
import 'dart:convert';
Paginations paginationsFromJson(String str) =>
Paginations.fromJson(json.decode(str));
String paginationsToJson(Paginations data) => json.encode(data.toJson());
class Paginations {
Paginations({
required this.pageIndex,
required this.pageSize,
required this.count,
required this.data,
});
int pageIndex;
int pageSize;
int count;
List<List<Patient>> data;
factory Paginations.fromJson(Map<String, dynamic> json) => Paginations(
pageIndex: json["pageIndex"],
pageSize: json["pageSize"],
count: json["count"],
data: List<List<Patient>>.from(json["data"]
.map((x) => List<Patient>.from(x.map((x) => Patient.fromJson(x))))),
);
Map<String, dynamic> toJson() => {
"pageIndex": pageIndex,
"pageSize": pageSize,
"count": count,
"data": List<dynamic>.from(
data.map((x) => List<dynamic>.from(x.map((x) => x.toJson())))),
};
}
class Patient {
Patient({
required this.id,
required this.hospitalId,
required this.hospitalName,
required this.firstName,
required this.lastName,
required this.doB,
required this.mobileNumber,
required this.gender,
required this.maritalStatus,
required this.primaryMember,
required this.membershipRegistrationNumber,
required this.address,
required this.divisionId,
required this.division,
required this.upazilaId,
required this.upazila,
required this.districtId,
required this.district,
required this.nid,
required this.bloodGroup,
required this.branchId,
required this.branchName,
required this.isActive,
required this.note,
required this.covidvaccine,
required this.vaccineBrand,
required this.vaccineDose,
required this.createdOn,
required this.createdBy,
required this.updatedOn,
required this.updatedBy,
required this.userName,
});
int id;
int hospitalId;
String hospitalName;
String firstName;
String lastName;
DateTime doB;
String mobileNumber;
String gender;
String maritalStatus;
bool primaryMember;
String membershipRegistrationNumber;
String address;
int divisionId;
String division;
int upazilaId;
String upazila;
int districtId;
String district;
String nid;
String bloodGroup;
int branchId;
String branchName;
bool isActive;
String note;
String covidvaccine;
String vaccineBrand;
String vaccineDose;
DateTime createdOn;
String createdBy;
DateTime updatedOn;
String updatedBy;
String userName;
factory Patient.fromJson(Map<String, dynamic> json) => Patient(
id: json["id"],
hospitalId: json["hospitalId"],
hospitalName: json["hospitalName"],
firstName: json["firstName"],
lastName: json["lastName"],
doB: DateTime.parse(json["doB"]),
mobileNumber: json["mobileNumber"],
gender: json["gender"],
maritalStatus: json["maritalStatus"],
primaryMember: json["primaryMember"],
membershipRegistrationNumber: json["membershipRegistrationNumber"],
address: json["address"],
divisionId: json["divisionId"],
division: json["division"],
upazilaId: json["upazilaId"],
upazila: json["upazila"],
districtId: json["districtId"],
district: json["district"],
nid: json["nid"],
bloodGroup: json["bloodGroup"],
branchId: json["branchId"],
branchName: json["branchName"],
isActive: json["isActive"],
note: json["note"],
covidvaccine: json["covidvaccine"],
vaccineBrand: json["vaccineBrand"],
vaccineDose: json["vaccineDose"],
createdOn: DateTime.parse(json["createdOn"]),
createdBy: json["createdBy"],
updatedOn: DateTime.parse(json["updatedOn"]),
updatedBy: json["updatedBy"],
userName: json["userName"],
);
Map<String, dynamic> toJson() => {
"id": id,
"hospitalId": hospitalId,
"hospitalName": hospitalName,
"firstName": firstName,
"lastName": lastName,
"doB": doB.toIso8601String(),
"mobileNumber": mobileNumber,
"gender": gender,
"maritalStatus": maritalStatus,
"primaryMember": primaryMember,
"membershipRegistrationNumber": membershipRegistrationNumber,
"address": address,
"divisionId": divisionId,
"division": division,
"upazilaId": upazilaId,
"upazila": upazila,
"districtId": districtId,
"district": district,
"nid": nid,
"bloodGroup": bloodGroup,
"branchId": branchId,
"branchName": branchName,
"isActive": isActive,
"note": note,
"covidvaccine": covidvaccine,
"vaccineBrand": vaccineBrand,
"vaccineDose": vaccineDose,
"createdOn": createdOn.toIso8601String(),
"createdBy": createdBy,
"updatedOn": updatedOn.toIso8601String(),
"updatedBy": updatedBy,
"userName": userName,
};
}
Get Data From API Code
loadPatient() async {
Paginations? pagination;
final response = await http.get(Uri.parse(PATIENTURI));
if (response.statusCode == 200) {
var jsonresponse = jsonDecode(response.body);
print(jsonresponse);
if (jsonresponse != null) {
pagination = Paginations.fromJson(jsonresponse);
print(pagination);
}
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
Error shows Bellow section inside Pagination Class
data: List<List>.from(json["data"] .map((x) => List.from(x.map((x) => Patient.fromJson(x))))),
Upvotes: 2
Views: 917
Reputation: 11994
X
is not a subtype of Y
is a very common exception. Let's understand what it means.
When you want to use X
where you need a Y
, but X
cannot fit into the Y
box, we get this exception.
Here are two cases in which we try to put a X
inside a Y
box.
X x = getSomeX();
Y y = x;
X x = getSomeX();
void giveMeY(Y y) {...}
giveMeY(x);
In these examples, we are trying to use an X
where we need a Y
.
So when you see "X
is not a subtype of Y
", flip it and say "oh I'm trying to do Y=X
somewhere".
Let's look at the line that you say this exception happened.
data: List<List>.from(json["data"].map((x) => List.from(x.map((x) => Patient.fromJson(x))))),
And this is the exception:
'(dynamic)=>Patient' is not a subtype of type '(String, dynamic)= MapEntry<dynamic, dynamic>'
You can see that you are trying to do
'(String, dynamic)= MapEntry<dynamic, dynamic>'
= (dynamic)=>Patient
So which one is your (dynamic)=>Patient
? There is only one there!
data: List<List>.from(json["data"].map((x) => List.from(x.map(
(x) => Patient.fromJson(x)
)))),
There is one other function there, but it's returning a List
, not a Patient
. So there is no doubt that we found the right function.
So, you would need to have another function there that looks more like this if you want to keep this structure. But this probably is not the solution, please read on.
data: List<List>.from(json["data"].map((x) => List.from(x.map(
(s, x) => MapEntry(s, Patient.fromJson(x))
)))),
This was just a guess, maybe it will even work. But this structure would require a function that looks like that.
Now why did this happen? Because you thought json["data"]
would contain a List
. Then a .map((e) => ..)
would make sense (docs). But in fact json["data"]
contains a Map
! Map
's .map()
function expects a function that gets two parameters (docs). Because we provided a function with a single parameter, we got this exception.
Now how would you practically solve this?
You thought json["data"]
was like this:
[{'name': 'patient1'}, {'name': 'patient2'}]
but it turns out it's something like this:
{'patients': [{'name': 'patient1'}, {'name': 'patient2'}]}
So you should find that key that I assumed might be 'patients'
, and get the list in it. Which would make your code something like this:
data: List<List>.from(json["data"].map((x) => List.from(x
['patients']
.map((x) => Patient.fromJson(x))))),
Upvotes: 3