我刚刚接触flutter,我认为这是一个新手问题。
我正在尝试获取在我的API上调用的数据并将其保存到我的模型中,但它有一个错误类型'List‘不是'Map’类型的子类型。
这是我的模型的副本
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']
);
}
}这是我的函数
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;
}
}这是我从API获得的示例数据
[{"ID":49,"FilePath":"20210903t171244.png","Notification":"ACT","WhenAdded":1630689165,"Status":"INA"}]发布于 2021-10-13 15:30:03
API返回JSON数组而不是json对象,因此是List而不是Map。
尝试:
if (res.statusCode == 200) {
print("Data Fetch!");
AdTemplate template = AdTemplate.fromJson(json.decode(utf8.decode(res.bodyBytes)));
return template;
}发布于 2021-10-13 15:54:55
您正在从您的API接收一个数组,这会导致错误。按如下方式更改以访问数组中的单个元素
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;
}
}发布于 2021-10-14 10:36:11
您的api返回一个列表
[{"ID":49,"FilePath":"20210903t171244.png","Notification":"ACT","WhenAdded":1630689165,"Status":"INA"}]在转换为模型之前,尝试像这样获取数据:data[0]或data.first
https://stackoverflow.com/questions/69557968
复制相似问题