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>
CodePudding user response:
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;
}
CodePudding user response:
[try check the image. in that i have changed the model as per map, List and null check. This will work iit is mostly because we are assigning the model wrongly. we have to tell the dart correctly which datatypes it is.
FYI: i tried posting code i couldn't it gave me warning so i shared image]1