這段代碼的主要作用是當 Firestore 上傳行程結束時,將頁面更改為 HomePage。但是我的“.then”代碼是無效的。
[代碼]
await Firestore.instance.collection('post').add(
{
'contents': textEditingController.text,
'displayName': widget.user.displayName,
'email': widget.user.email,
'photoUrl': downloadUrl,
'userPhotoUrl': widget.user.photoUrl,
});
} else {
await Firestore.instance.collection('post').add({
'contents': textEditingController.text,
'displayName': widget.user.displayName,
'email': widget.user.email,
'photoUrl': 'https://firebasestorage.googleapis.com/v0/b/woonsancommunity2-c95f8.appspot.com/o/post/No IMG.001.png?alt=media&token=47a39955-39a0-447f-8846-d89149f40ee3',
'userPhotoUrl': widget.user.photoUrl,
}).then(() {
Navigator.push(
context, MaterialPageRoute(builder:(context) =>
HomePage(widget.user)),
);
});
}
在這種情況下,.then 代碼無效。(灰色字體顏色).. 請幫幫我!
uj5u.com熱心網友回復:
then()
由于您等待添加到集合的程序,因此呼叫該方法毫無意義。
只需從方法中移出 Navigator 推送方法,then()
并洗掉then()
.
回呼 inthen()
用于在前一個 Future 完成時呼叫,但由于您等待 Future,您可以保證在 Future 完成時呼叫之后的陳述句
uj5u.com熱心網友回復:
看起來您正在將 Promise/Future 與異步代碼結合起來。
如果你放在await
Future 之前,它會等待它解決,然后根據它所做的回傳錯誤或結果。
要修復您的代碼,請await
像這樣使用。
const result = await ...; // remove then block
if(result){
// Your then block code here
}
或者你可以洗掉await
uj5u.com熱心網友回復:
首先,它的冗余使用await
和then
相同的功能。
await
: 是為了中斷流程直到異步方法完成then
: 不會中斷行程,但使您能夠在異步完成時運行代碼
閱讀本文以獲得更多解釋和演示:await vs then in Flutter
您的代碼中的錯誤是,您使用then
錯誤的方式。這應該是:
Future<R> then<R>(FutureOr<R> Function(String) onValue, {Function? one rror})
解決方案:
}).then((value) { // you miss the "value"
Navigator.push(
context, MaterialPageRoute(builder:(context) =>
HomePage(widget.user)),
);
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/529302.html
標籤:扑镖
上一篇:水平ListView.Builder()在Flutter中不起作用
下一篇:如何使按鈕被選中?