我只是想在這個函式中設定一個 ID:
_getLastWorkoutId() async {
try {
var snapshot = await usersRef
.doc(currentUser!.uid)
.collection('workouts')
.orderBy('workoutDate', descending: true)
.limit(1)
.snapshots()
.first;
//The execution moves to build method from here------and then returns
for (var element in snapshot.docs) {
workoutId = element.id;
setState(() {
_isWorkoutIdSet = true;
});
}
//return snapshot;
} catch (e) {
print(e.toString());
}
//return null;
}
我在 initState 中呼叫它:
@override
void initState() {
WidgetsBinding.instance!.addObserver(this);
super.initState();
//var snapshot = _getLastWorkoutId();
_getLastWorkoutId();
}
問題是,for 回圈在呼叫構建函式后執行。我不希望這種情況發生。
uj5u.com熱心網友回復:
你可以這樣使用FutureBuilder:
Future<bool> _value;
@override
void initState() {
WidgetsBinding.instance!.addObserver(this);
super.initState();
_value = _getLastWorkoutId();
}
在你的build方法中,你有:
FutureBuilder<bool>(
future: _value,
builder: (
BuildContext context,
AsyncSnapshot<bool> snapshot,
) {
if (snapshot.hasData) {
if (snapshot.data){
//update view
}else{
//update view
}
}
}
該方法可以是這樣的:
_getLastWorkoutId() async {
try {
var snapshot = await usersRef
.doc(currentUser!.uid)
.collection('workouts')
.orderBy('workoutDate', descending: true)
.limit(1)
.snapshots()
.first;
for (var element in snapshot.docs) {
workoutId = element.id;
return true;
}
} catch (e) {
print(e.toString());
}
}
在這里你可以找到更多關于FutureBuilder.
uj5u.com熱心網友回復:
我相信這應該可以解決問題:
首先,關于構建方法:
return FutureBuilder(
future: _getLastWorkoutId(),
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) return CircularProgressIndicator();
return Container(); // here goes whatever it is you had before.
}
);
然后_getLastWorkoutId():
Future<void> _getLastWorkoutId() async {
...
}
這樣,函式回傳一個 void 而不是 void 的未來,允許FutureBuilder做它的事情。
uj5u.com熱心網友回復:
您應該宣告一個變數來保存狀態。例如
var isLoading = true;
在 func _getLastWorkoutId 中的 try 塊結束時,將 isLoading 重置為 false。然后通過更好的方式呼叫 setState 或更新狀態,使用狀態管理,如 provider、bloc、get。在構建小部件中添加檢查 isLoading 像這樣
return isLoading ? YourLoadingIndicatorWidget() : DisplayDataWidget();
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/383456.html
