【发布时间】:2022-01-12 15:59:33
【问题描述】:
我在通过事务写入 Firestore 时遇到了一些问题。我正在尝试通过将 otherUserID 添加到用户的文档数组中来更新属于用户的集合中的所有文档。用户的文档数组没有更新,经过一些调试,我发现问题是“断点 2”下面的代码在“断点 1”之前执行,这意味着事务更新永远不会发生,因为 dataList 仍然是空的。
但是从代码的编写方式来看,forEach中的代码不应该先完成“断点1”吗?
Future<void> updateData(User myUser, String otherUserID) async {
List<Data> dataList = [];
QuerySnapshot<Map<String, dynamic>> otherDataQuery =
await FirebaseFirestore.instance
.collection('data')
.where('userID', isEqualTo: myUser.userID)
.get();
await FirebaseFirestore.instance.runTransaction(
(transaction) async {
otherDataQuery.docs.forEach(
(document) async {
Data oldData = Data.fromMap(
document.data(),
);
DocumentSnapshot snapshot = await transaction.get(
dataRef.doc(oldData.ID),
);
Data thisData =
Data.fromMap(snapshot.data() as Map<String, dynamic>);
thisData.users!.add(otherUserID);
dataList.add(thisData);
print('Breakpoint 1');
print(dataList.length);
},
);
print('Breakpoint 2');
print(dataList.length);
for (var i = 0; i <= dataList.length - 1; i++) {
await transaction.update(
dataRef.doc(dataList[i].ID),
{'usersList': dataList[i].users},
);
}
},
timeout: Duration(seconds: 10),
);
}
【问题讨论】:
标签: flutter google-cloud-firestore