您好,我有一個“while 回圈”,它只發生一次,我不知道為什么,它假設發生了 12 次,但它沒有。為什么???
這是我的代碼:
Future<List<Evsebillall>> fetcheach() async {
int i=1;
while (i<12) {
print(i);
i ;
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/contractedChargeTransactions?month=$i&year=2022'),
headers: headers);
if (response.statusCode == 200) {
setState(() {
cardBillsTotaleach = jsonDecode(response.body)["cardBillsTotal"] as List;
var resultTotal = cardBillsTotaleach.map((e) => Evsebill.fromJson(e)).toList();
if(resultTotal.isNotEmpty) {
TotalTotaleach = (resultTotal[0].total);
print("totaleach =$TotalTotaleach");
Totaleachlist.add(TotalTotaleach);
}
print ("listtotal =$Totaleachlist");
});
return cardBillsall.map((e) => Evsebillall.fromJson(e)).toList();
}
else{
throw Exception('Failed to load Bills');
}
}
throw Exception('Failed to load Bills');
}
uj5u.com熱心網友回復:
發生這種情況是因為您在回圈內呼叫 return 因此在第一輪回傳時,它會停止回圈。嘗試這個:
Future<List<Evsebillall>> fetcheach() async {
int i = 1;
List<Evsebillall> result = []; // <--add this
while (i < 12) {
print(i);
i ;
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/contractedChargeTransactions?month=$i&year=2022'),
headers: headers);
if (response.statusCode == 200) {
setState(() {
cardBillsTotaleach =
jsonDecode(response.body)["cardBillsTotal"] as List;
var resultTotal =
cardBillsTotaleach.map((e) => Evsebill.fromJson(e)).toList();
if (resultTotal.isNotEmpty) {
TotalTotaleach = (resultTotal[0].total);
print("totaleach =$TotalTotaleach");
Totaleachlist.add(TotalTotaleach);
}
print("listtotal =$Totaleachlist");
});
result.addAll(cardBillsall.map((e) => Evsebillall.fromJson(e)).toList());// <--add this
} else {
throw Exception('Failed to load Bills');
}
}
return result;// <--add this
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/515994.html
標籤:扑镖
