I have the following JSON that is getting returned from an API call:
{
"categories": {
"mortgage": "Mortgage",
"haircutsClothing": "Haircuts & Clothing",
"homeRepairMaintenance": "Home Repair & Maintenance"
},
"other": {...}
}
And then I have this class acting as a model for the JSON data:
class APIData {
final Map<String, dynamic> parsedJson;
APIData({required this.parsedJson});
factory APIData.fromJson(Map<String, dynamic> parsedJson) {
List<Category> categories = parsedJson['categories']
.map((i) => Category.fromJson(i))
.toList();
return APIData(parsedJson: parsedJson);
}
}
class Category {
final String key;
final String category;
Category({required this.key, required this.category});
factory Category.fromJson(Map<String, dynamic> parsedJson) {
return Category(key: parsedJson['key'], category: parsedJson['value']);
}
}
When I run that, I get this error:
_TypeError (type '(dynamic) => Category' is not a subtype of type '(String, dynamic) => MapEntry<dynamic, dynamic>' of 'transform')
What am I doing wrong that is causing this error?
CodePudding user response:
method .map on Map object has to return Map object too.
try this
final categoriesMap = parsedJson['categories'] as Map;
final List<Category> categories =
categoriesMap.entries
.map((e) => Category(key: e.key, category: e.value))
.toList();
entries from a Map returns an Iterable of Map Entry. then you can iterate through it and use key and value properties.