How can I save two records with the id of the other in flutter?
I'm trying to save two records with id of the other, I can do that, but when I try to save more than 2 at same time some id come with blank. This is my code:
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] },
);
CodePudding user response:
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] },
);
CodePudding user response:
Consider using the set()
method provided the cloud firestore api.
Usage Example from the reference.
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"));
For saving more than one document consider coupling it with the Future
wait
for a clean code.
/// 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);