你好,我正在尝试将我的请求保存到我的列表中,但是它说未处理的异常:类型'String‘不是'index’的'int‘类型的子类型。
你好,我正在尝试将我的请求保存到我的列表中,但是它说未处理的异常:类型'String‘不是'index’的'int‘类型的子类型。
这是我的班:
class Evsebill {
final String serial;
final double value;
final double vat;
final double total;
final int energy;
const Evsebill({
required this.serial,
required this.value,
required this.vat,
required this.total,
required this.energy
});
factory Evsebill.fromJson(Map<String, dynamic> json) {
return Evsebill(
serial: json['serial'] as String,
value: json['value']as double,
vat: json['vat']as double,
total: json['total']as double,
energy: json['energy']as int,
);
}
}
以下是我的要求:
List<Evsebill> parseBills(String responseBody) {
final parsed = jsonDecode(responseBody)["results"]["cardBillsTotal"].cast<Map<String, dynamic>>();
return parsed.map<Evsebill>((json) => Evsebill.fromJson(json)).toList();
}
Future<List<Evsebill>> fetch() async {
String? token = await this.storage.read(key: "token");
Map<String, String> headers = {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": "Bearer " + (token ?? ""),
};
final response = await http.get(Uri.parse(
this.serverIP + ':' + this.serverPort +
'/user/contractedChargeTransactionsList?page=1&limit=10&year=eq:2022'),
headers: headers);
if (response.statusCode == 200) {
setState(() {
print(response.body);
cardBills = jsonDecode(response.body)["results"]["cardBillsTotal"] as List;
var result = cardBills.map((e) => Evsebill.fromJson(e)).toList();
});
return cardBills.map((e) => Evsebill.fromJson(e)).toList();
}
else{
throw Exception('Failed to load Bills');
}
}
这是我的印刷品(response.body);
I/flutter (19587): {"results":[{"firstName":"Θωμάς","lastName":"Παπαϊωάννου","userID":238,"month":5,"year":2022,"cardBillsTotal":[{"serial":"884221337251","value":1.0450,"vat":0.2508,"total":1.2958,"energy":0}]},{"firstName":"Θωμάς","lastName":"Παπαϊωάννου","userID":238,"month":6,"year":2022,"cardBillsTotal":[{"serial":"884221337251","value":3.4034,"vat":0.8168,"total":4.2202,"energy":0}]},{"firstName":"Θωμάς","lastName":"Παπαϊωάννου","userID":238,"month":7,"year":2022,"cardBillsTotal":[{"serial":"884221337251","value":2.0900,"vat":0.5016,"total":2.5916,"energy":0}]},{"firstName":"Θωμάς","lastName":"Παπαϊωάννου","userID":238,"month":5,"year":2022,"cardBillsTotal":[{"serial":"941368618045","value":2.2884,"vat":0.5492,"total":2.8376,"energy":0}]},{"firstName":"Θωμάς","lastName":"Παπαϊωάννου","
发布于 2022-10-13 04:04:05
您应该迭代您的http reponse,因为它是一个列表,并且首先您应该访问每个元素。所以不是这些,
cardBills = jsonDecode(response.body)["results"]["cardBillsTotal"] as List;
//cardBillsTotal = jsonDecode(response.body)["cardBillsTotal"] as List;
month = jsonDecode(response.body)['month'];
userid = jsonDecode(response.body)['userID'];
你应该有这样的东西:
final response = jsonDecode(response.body)["results"];
(response as List<dynamic>).forEach((e) {
month = e['month'];
userid = e['userID'];
//and so on
})
.toList()
我想你明白主要的想法了。
https://stackoverflow.com/questions/74055241
复制