gpt4 book ai didi

dart - 如何向 firestore 中的现有数组添加或删除项目?

转载 作者:IT王子 更新时间:2023-10-29 06:36:06 29 4
gpt4 key购买 nike

Firestore 最近添加了新方法 FieldValue.arrayUnion(value) 和 FieldValue.arrayRemove(value) 但我在 flutter cloud_firestore 包中找不到实现。有什么办法可以达到这个结果吗?

Firestore 添加更新:https://firebase.google.com/docs/firestore/manage-data/add-data#update_elements_in_an_array

最佳答案

这里是展示如何更新数组值的简单示例。我的文档有一个 up voters 数组,用于添加对文档进行 up-votes 的用户 ID。

配置 firestore,可以从您的 google-services.json 文件中复制配置详细信息

   final FirebaseApp app = await FirebaseApp.configure(
name: 'test',
options: const FirebaseOptions(
projectID: 'projid',
googleAppID: 'appid',
apiKey: 'api',
databaseURL: 'your url',
),
);
final Firestore firestore = Firestore(app: app);

await firestore.settings(timestampsInSnapshotsEnabled: true);

使用事务更新代码

fireStore.runTransaction((Transaction tx) async {
DocumentSnapshot snapshot =
await tx.get(widget._document.reference);
var doc = snapshot.data;
if (doc['upvoters'].contains('12345')) {
await tx.update(snapshot.reference, <String, dynamic>{
'upvoters': FieldValue.arrayRemove(['12345'])
});
} else {
await tx.update(snapshot.reference, <String, dynamic>{
'upvoters': FieldValue.arrayUnion(['12345'])
});
}
});

希望对你有帮助

关于dart - 如何向 firestore 中的现有数组添加或删除项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52150545/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com