我目前正在使用Flutter和firebase。我正在尝试将一些数据上传到云firestore。到目前为止一切顺利。当我想向字段添加列表时,我遇到了一个问题。如前所述,此字段包含如下定义的值列表:
Map<String, Object> toDocument() {
Map customerAddress = Map();
Map orderCheckoutDetails = Map();
final DateTime now = DateTime.now();
final DateFormat formatter = DateFormat('dd-MM-yyyy');
final String formatted = formatter.format(now);
customerAddress['address'] = this.address;
customerAddress['city'] = this.city;
customerAddress['state'] = this.state;
customerAddress['zipCode'] = this.zipCode;
orderCheckoutDetails['checkoutOrderDate'] = formatted;
orderCheckoutDetails['customerAddress'] = customerAddress;
orderCheckoutDetails['customerName'] = '${this.nome!} ${this.cognome!}';
orderCheckoutDetails['customerPhone'] = this.numeroTelefono!;
orderCheckoutDetails['products'] = this.products!.map((product) => product.name).toList();
orderCheckoutDetails['subtotal'] = this.subtotal!;
orderCheckoutDetails['deliveryFee'] = this.deliveryFee!;
orderCheckoutDetails['total'] = this.total!;
List<Map<dynamic, dynamic>> orderList = [orderCheckoutDetails];
return {
'orderCheckoutDetails': orderList,
};
}
这是它在Firebase上向我显示项目的方式(这是正确的)。enter image description here
这就是我如何将文档上传到Firebase。
@override
Future<void> addCheckout(Checkout checkout) async {
print(checkout.email!);
final docExists = await _checkIfUserCheckoutExists(checkout.email!);
print(docExists);
if (!docExists) {
return _checkoutCollection
.doc(checkout.email!)
.set(checkout.toDocument());
} else {
await _checkoutCollection.doc(checkout.email!).update({
"orderCheckoutDetails":
FieldValue.arrayUnion(checkout.toDocument() as List)
});
}
}
我想做的是在文档末尾追加一个元素(参数传递的checkout元素),怎么做?
2条答案
按热度按时间0x6upsns1#
你可以在两种情况下使用
set
和merge选项(无论文档是否存在),它将根据需要创建或更新文档。另外,你的toDocument
方法应该返回orderList
本身,而不是你当前返回的map。试试这个:
然后创建/插入您的文档,如下所示:
zzoitvuj2#
尝试在firebase文档中以这种方式使用FieldValue.arrayUnion([data])
阅读更多在这里输入链接描述这里