I have a list which is like this below:
{
"results": [
{
"firstName": "Thomas",
"lastName": "Papioanou",
"userID": 238,
"month": 5,
"year": 2022,
"cardBillsTotal": [
{
"serial": "884221337251",
"value": 1.0450,
"vat": 0.2508,
"total": 1.2958,
"energy": 0
}
]
},
{
"firstName": "Thomas",
"lastName": "Papioanou",
"userID": 238,
"month": 6,
"year": 2022,
"cardBillsTotal": [
{
"serial": "884221337251",
"value": 3.4034,
"vat": 0.8168,
"total": 4.2202,
"energy": 0
}
]
},
{
"firstName": "Thomas",
"lastName": "Papioanou",
"userID": 238,
"month": 7,
"year": 2022,
"cardBillsTotal": [
{
"serial": "884221337251",
"value": 2.0900,
"vat": 0.5016,
"total": 2.5916,
"energy": 0
}
]
},
{
"firstName": "Thomas",
"lastName": "Papioanou",
"userID": 238,
"month": 5,
"year": 2022,
"cardBillsTotal": [
{
"serial": "941368618045",
"value": 2.2884,
"vat": 0.5492,
"total": 2.8376,
"energy": 0
}
]
},
{
"firstName": "Thomas",
"lastName": "Papioanou",
"userID": 238,
"month": 6,
"year": 2022,
"cardBillsTotal": [
{
"serial": "941368618045",
"value": 1.1083,
"vat": 0.2660,
"total": 1.3743,
"energy": 0
}
]
}
],
"count": 5
}
If month = 5 I want to store the bracket '[cardBillsTotal]', how can I do that?
Here is my request and code if you needed:
Future<List<Evsebillall>> fetchall() 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'),
headers: headers);
if (response.statusCode == 200) {
setState(() {
cardBillsall = jsonDecode(response.body)["results"] as List;
print(cardBillsall);
var result = cardBillsall.map((e) => Evsebillall.fromJson(e)).toList();
print (data);
});
return cardBillsall.map((e) => Evsebillall.fromJson(e)).toList();
}
else{
throw Exception('Failed to load Bills');
}
}
I tried something like this but it didn't work out:
var data = cardBillsall.map((e) => e["month"]=5).toList();
CodePudding user response:
Try this:
var data = cardBillsall.where((element) => element["month"]== 5).toList();
var cardBillsTotalList = [];
for (var item in data) {
cardBillsTotalList.addAll(item['cardBillsTotal'] as List);
}
if you print cardBillsTotalList
you will get this:
print("cardBillsTotalList =$cardBillsTotalList"); //cardBillsTotalList =[{serial: 884221337251, value: 1.045, vat: 0.2508, total: 1.2958, energy: 0}, {serial: 941368618045, value: 2.2884, vat: 0.5492, total: 2.8376, energy: 0}]