如何保存两条记录,其中一条的id处于抖动状态?



如何保存两条记录与另一条记录的id在flutter中?

我试图保存两个记录与id的另一个,我可以这样做,但当我试图保存超过2同时一些id来与空白。这是我的代码:

collectionReferenceRel.add({
'idRoom': id,
'room': rel,
'rel': room,
'id': '',
}).then((idRel) {
idRel1 = idRel.id;
},
);
collectionReferenceRel.add({
'idRoom': id,
'room': room,
'rel': rel,
'id': '',
}).then((value2) {
idNode2 = value2.id;
}).whenComplete(() async {
await collectionReferenceRel.doc(idRel1).update({
'id': idRel2,
});
await collectionReferenceRel.doc(idRel2).update({
'id': idRel1,
});
}).catchError((error) {
CustomFullScreenDialog.cancelDialog();
CustomSnackBar.showSnackBar(
context: Get.context,
title: 'Error',
message: 'Something went wrong',
backgroundColor: Colors.green);
[![enter image description here][1]][1] }, 
);

https://api.flutter-io.cn/flutter/dart-async/Future/wait.html


Future.wait([
collectionReferenceRel.add({
'idRoom': id,
'room': rel,
'rel': room,
'id': '',
}).then((idRel) {
idRel1 = idRel.id;
},
),
collectionReferenceRel.add({
'idRoom': id,
'room': room,
'rel': rel,
'id': '',
}).then((value2) {
idNode2 = value2.id;
})
]).whenComplete(() async {
await collectionReferenceRel.doc(idRel1).update({
'id': idRel2,
});
await collectionReferenceRel.doc(idRel2).update({
'id': idRel1,
});
}).catchError((error) {
CustomFullScreenDialog.cancelDialog();
CustomSnackBar.showSnackBar(
context: Get.context,
title: 'Error',
message: 'Something went wrong',
backgroundColor: Colors.green);
[![enter image description here][1]][1] }, 
);

考虑使用云存储api提供的set()方法。

用法示例参考。

final city = <String, String>{
"name": "Los Angeles",
"state": "CA",
"country": "USA"
};
db.collection("cities")
.doc("LA")
.set(city)
.onError((e, _) => print("Error writing document: $e"));

为了保存多个文档,考虑将其与Futurewait耦合以获得干净的代码。

/// Create a list to add all documents
final List docs = [];

/// create the documents with unique identifiers 
/// beforehand using a package such as `Uuid`
final docA = {
'id': 'unique_identifier_a',
'idRoom': id,
'room': rel,
'rel': room,
}
docs.add(docA);
final docB = {
'id': 'unique_identifier_b',
'idRoom': id,
'room': rel,
'rel': room,
}
docs.add(docB);
/// Create futures from the documents
final futures = docs.map((e) => collectionRef.doc(e.id).set(e));

/// Save the documents in shot and wait for all
await Future.wait(futures);

相关内容

  • 没有找到相关文章

最新更新