更新时间:2023-12-01 09:13:58
这里是一个简单的例子,展示了如何更新数组值.我的文档有一个投票者数组,用于添加对文档进行投票的用户 ID.
Here is the simple example to show how to update the array values. My document have an up voters array to add the user id's who have up-votes the document.
配置 firestore,可以从您的 google-services.json 文件中复制配置详细信息
configure firestore, the config details can be copied form your google-services.json file
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'])
});
}
});
希望能帮到你