I got an error when I try to fix the error on my ApiProvider, this is my ApiProvider:
class ApiProvider {
final Dio _dio = Dio();
final String _url = 'http://lovemonster.my.id/hospital';
Future<List<HospitalListModel>> fetchHospitalList() async {
try {
List<HospitalListModel> hospitalList = [];
Response response = await _dio.get(_url);
var mData = response.data as List;
hospitalList = mData.map<HospitalListModel>((e) => hospitalListModelFromJson(e))
.toList();
return hospitalList;//return List not object
} catch (error, stacktrace) {
print("Exception occurred: $error stackTrace: $stacktrace");
return Future.error("");
}
}
and the error is on hospitalListModelFromJson(e)
, it related to hospitalListModelFromJson
from my model, i just want to create a listview from this API http://lovemonster.my.id/hospital, this is my model:
List<HospitalListModel> hospitalListModelFromJson(String str) => List<HospitalListModel>.from(json.decode(str).map((x) => HospitalListModel.fromJson(x)));
String hospitalListModelToJson(List<HospitalListModel> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class HospitalListModel {
HospitalListModel({
this.id,
this.title,
this.content,
this.image,
this.phone,
this.coordinates,
this.website,
this.createdAt,
this.updatedAt,
});
dynamic id;
dynamic title;
dynamic content;
dynamic image;
dynamic phone;
dynamic coordinates;
dynamic website;
dynamic createdAt;
dynamic updatedAt;
factory HospitalListModel.fromJson(Map<String, dynamic> json) => HospitalListModel(
id: json["id"],
title: json["title"],
content: json["content"],
image: json["image"],
phone: json["phone"],
coordinates: json["coordinates"],
website: json["website"],
createdAt: json["created_at"],
updatedAt: json["updated_at"],
);
Map<String, dynamic> toJson() => {
"id": id,
"title": title,
"content": content,
"image": image,
"phone": phone,
"coordinates": coordinates,
"website": website,
"created_at": createdAt.toIso8601String(),
"updated_at": updatedAt.toIso8601String(),
};
}
if you know how to fetch the model into list or you know how to fix the error, please let me know
CodePudding user response:
You need to change these:
var mData = response.data as List;
hospitalList = mData.map<HospitalListModel>((e) => hospitalListModelFromJson(e))
.toList();
to this:
hospitalList = hospitalListModelFromJson(response.data)
Fist of all you api response is not list
is encoded list
, second you convert it twice into the list and this is cause the issue.
edit:
change this :
List<HospitalListModel> hospitalListModelFromJson(String str) => List<HospitalListModel>.from(json.decode(str).map((x) => HospitalListModel.fromJson(x)));
to this:
List<HospitalListModel> hospitalListModelFromJson(List<Map<String, dynamic>> data) => List<HospitalListModel>.from(data.map((x) => HospitalListModel.fromJson(x)));
from your second error, it seems your api response isn't encoded so you don't need to decode it.