我正在嘗試生成隨機整數并檢查該整數是否存在于 Firebase 資料庫中,并無限執行此操作,直到該整數不存在于資料庫中。
在我的代碼下面:
while (true) {
_changeRandomInt()
firebaseFirestore.collection("myCollection").doc(_randomInt).get().then((DocumentSnapshot documentSnapshot) {
if (getFromFirebase(documentSnapshot) == null) {
break;
}
});
}
但我什至無法運行這段代碼。錯誤:A break statement can't be used outside of a loop or switch statement. Try removing the break statement.我在 while 回圈中中斷了,那么為什么會出現此錯誤?如何解決這個問題?
uj5u.com熱心網友回復:
break 陳述句不能在回圈或 switch 陳述句之外使用。嘗試洗掉 break 陳述句。
這是不言自明的。您不能在回圈之外使用 break。在你的情況下,這是在未來。
做這樣的事情:
_changeRandomInt();
firebaseFirestore.collection("myCollection").doc(_randomInt).get()
.then((DocumentSnapshot documentSnapshot) {
while (getFromFirebase(documentSnapshot) != null){
//the body of this loop will only execute as long as the value isn't null
//will break out of the loop as soon as the value is null
}
}
uj5u.com熱心網友回復:
在break你用的是內部的then(),這意味著沒有回路可立即突破上方`。您可以以這種方式重構代碼以使其正常作業。
while (true) {
_changeRandomInt()
final documentSnapshot = await firebaseFirestore.collection("myCollection").doc(_randomInt).get();
if (getFromFirebase(documentSnapshot) == null) {
break;
}
}
如果getFromFirebase也是一個未來,那么在 if 塊中也等待它。
uj5u.com熱心網友回復:
你想做這樣的事情:
void functionName() async {
try{
var ans;
while(getFromFirebae(ans)== null){
ans = await firebaseFirestore.collection("myCollection").doc(_randomInt).get();
}
} catch(e){
//error
}
}
然而,這不是正確的方法。一個好的做法是創建一個加載小部件,它會在未來加載時顯示影片。更好的方法 - 在后臺加載所有內容而不會拖延整個應用程式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/383558.html
