根據問題,我想在每次呼叫 addPredection 函式時添加一個新陣列,例如,我希望它看起來像這樣。
目前它只是每次更新當前值

我的代碼如下:
///add prediction function
Future<String?> addPrediction() async {
var currentUser = FirebaseAuth.instance.currentUser;
var todaysDate = DateTime.now().toString();
var doesExist = await FirebaseFirestore.instance
.collection('collection')
.doc(currentUser!.uid)
.get();
if (doesExist.exists == true) {
FirebaseFirestore.instance
.collection('userMoods')
.doc(currentUser!.uid)
.update({
'Predictions':
FieldValue.arrayUnion([todaysDate,'angry', 'Happy'])
});
}
if (doesExist.exists == false) {
FirebaseFirestore.instance
.collection('userMoods')
.doc(currentUser!.uid)
.set({
todaysDate: FieldValue.arrayUnion(['angry', 'Happy'])
}, SetOptions(merge: false));
}
uj5u.com熱心網友回復:
要添加專案,您還必須應用SetOptions但合并設定為 true,如下所示:
var todaysDate = DateTime.now().toString();
FirebaseFirestore.instance
.collection('userMoods')
.doc(currentUser!.UID).set({
todaysDate : ['angry', 'happy']
}, SetOptions(merge: true));
我最終做到了,我相信它們會以您想要的方式出現:

SetOptions上的merge: true它所做的是附加到現有檔案。默認情況下,set方法會覆寫現有欄位,除非存在merge: true選項。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/425708.html
