I'm just new in flutter and I think this is a newbie question.
I'm trying to get the data that I call on my API and save it to my model but it's having an error type 'List' is not a subtype of type 'Map<dynamic, dynamic>'
Here is the copy of my model
class AdTemplate{
final int id;
final String filePath;
final String notification;
final String status;
final int whenAdded;
AdTemplate(
{this.id,
this.filePath,
this.notification,
this.status,
this.whenAdded});
factory AdTemplate.fromJson(Map<String, dynamic> json) {
return AdTemplate(
id: json['ID'],
filePath: json['FilePath'],
notification: json['Notification'],
status: json['Status'],
whenAdded: json['WhenAdded']
);
}
}
And this is my function
Future<AdTemplate> getActiveBannerNotif() async {
try {
String url = 'https://api/path/';
var res = await http.get(url);
final Map data = convert.jsonDecode(res.body);
if (res.statusCode == 200) {
print("Data Fetch!");
AdTemplate template = AdTemplate.fromJson(data);
return template;
} else {
print('No data.');
return null;
}
} catch (e) {
print(e);
return null;
}
}
This is the sample data that I get from the API
[{"ID":49,"FilePath":"20210903t171244.png","Notification":"ACT","WhenAdded":1630689165,"Status":"INA"}]
CodePudding user response:
API returns JSON array not json object so that is List not Map.
try :
if (res.statusCode == 200) {
print("Data Fetch!");
AdTemplate template = AdTemplate.fromJson(json.decode(utf8.decode(res.bodyBytes)));
return template;
}
CodePudding user response:
You are receiving an array from your API and that causes the error. change as following to access a single element from array
Future<AdTemplate> getActiveBannerNotif() async {
try {
String url = 'https://api/path/';
var res = await http.get(url);
if (res.statusCode == 200) {
print("Data Fetch!");
final data = convert.jsonDecode(res.body);
AdTemplate template = AdTemplate.fromJson(data[0]);
return template;
} else {
print('No data.');
return null;
}
} catch (e) {
print(e);
return null;
}
}