I need to convert a web API to modal. I am using dio for fetch it and here is the fetch output from dio:
{
success: true,
status: 200,
message: "Category is ready to show",
data: [
{id: 5, name: Pharmacy, img: sub_cat1705749441.png, color: #e5edfa},
{id: 6, name: Seafood, img: sub_cat1705749543.png, color: #ffeddd}
]
}
then in repository I use the following code to modal the API fetch:
final allSubCatListApi = await homeApi.getSubCatApi();
var responseJson =
allSubCatListApi['data'].map((e) => SubCatModal.fromjson(e)).toList();
Here is the output:
Instance of 'SubCatModal', Instance of 'SubCatModal', Instance of 'SubCatModal', Instance of 'SubCatModal']
So, it is modelling well but the type of responseJson
is still List<dynamic>
not List<SubCatModal>
, so I need to convert the type to be List<SubCatModal>
.
Here is the modal:
class SubCatModal {
late int id;
late String name;
late String img;
late String color;
SubCatModal.fromjson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
img = json['img'];
color = json['color'];
}
}
You need to provide SubCatModal
as generic type parameter to the map
method (https://api.dart.dev/stable/3.2.5/dart-core/Iterable/map.html):
List<SubCatModal> responseJson =
allSubCatListApi['data'].map<SubCatModal>((e) => SubCatModal.fromjson(e)).toList();