【发布时间】:2021-12-02 01:54:05
【问题描述】:
我只是 Flutter 的新手,我认为这是一个新手问题。
我正在尝试获取我在 API 上调用的数据并将其保存到我的模型中,但它的错误类型为“列表”不是“地图”类型的子类型
这是我的模型的副本
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"}]
【问题讨论】:
-
错误在哪一行?
-
@MiguelEscobarCalderon 这一行 AdTemplate template = AdTemplate.fromJson(data);
-
你能把你的 JSON 字符串添加到问题中吗
-
@rosh-dev 我添加了它。
-
您正在接收一个数组。导致错误。更改您的 API 或代码