I am Practicing to building an app, in which I need to read data from API. I am trying to parse data through JSON
here is link of the api : https://fakestoreapi.com/products
Here is the model class :
class ProductModel {
int id = 0;
String title = "";
double price = 0;
String description = "";
String category = "";
String image = "";
List<Rating> rating = [];
ProductModel.fromJson(Map<String, dynamic> json) {
id = json['id'];
title = json['title'];
price = json['price'];
description = json['description'];
category = json['category'];
image = json['image'];
rating = List.from(json['rating']).map((e) => Rating.fromJson(e)).toList();
}
Map<String, dynamic> toJson() {
final data = <String, dynamic>{};
data['id'] = this.id;
data['title'] = this.title;
data['price'] = this.price;
data['description'] = this.description;
data['category'] = this.category;
data['image'] = this.image;
data['rateing'] = rating.map((e) => e.toJson()).toList();
return data;
}
}
class Rating {
double rate = 0;
int count = 0;
Rating.fromJson(Map<String, dynamic> json) {
rate = json['rate'];
count = json['count'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['rate'] = this.rate;
data['count'] = this.count;
return data;
}
}
Here is the api call function :
Future getAllProduct() async {
try {
Response response = await _dio.get(_baseUrl);
if (response.statusCode == 200 && response.data !== null) {
print(response.data);
return ProductModel.fromJson(response.data);
} // error response must be used in the production
else {
return response.statusCode.toString();
}
} on DioError catch (error, stacktrace) {
print("Exception occured: $error StackTrace: $stacktrace");
}
}
The error I am currently facing is :
List<dynamic>' is not a subtype of type 'Map<String, dynamic>
because response.data is list of ProductModel
try this:
Future<List<ProductModel>> getAllProduct() async {
List<ProductModel> _list = [];
try {
Response response = await _dio.get(_baseUrl);
if (response.statusCode == 200 && response.data !== null) {
response.data.forEach((e){
_list.add(ProductModel.fromJson(e));
});
} // error response must be used in the production
else {
return [];
}
} on DioError catch (error, stacktrace) {
print("Exception occured: $error StackTrace: $stacktrace");
}
return _list;
}
When the response is successful, you can return it as follows:
return (response.data as List).map((e) => ProductModel.fromJson(e)).toList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With