Issue
Is it possible to write to a Cloud Firestore NEW document subcollection while user is offline?
In my app, the user will add a new document with items being added to the document's subcollection. Everything works fine when the device is online. But when offline, the first level collection document seems to be added as expected, however the subcollection items are not added until the devise is back online.
I understand that Firestore have offline persistence enabled by default and it will write documents to cache if the device loses connectivity. But is it only able to write the documents to the first level collections? Can I add to the subcollection without awaiting until the new document is written on the server (i.e. use cache reference) since the persistence feature is not working with async/await functions?
Below is my sample code for writing to Cloud Firestore. I am not able to fetch the subcollections until back online - the data from get() will return empty.
Can anyone please help me with this? Apologies if this has been answered somewhere - I couldn’t find it.
void main() async {
await Firebase.initializeApp();
FirebaseFirestore _firestore;
_firestore = FirebaseFirestore.instance;
runApp(
MultiProvider(
providers: [
Provider<MyFirestoreFunctions>(create: (_) => MyFirestoreFunctions(_firestore)),
],
child: MyApp(),
),
);
}
class MyFirestoreFunctions {
MyFirestoreFunctions(this._firestore) : assert(_firestore != null);
final FirebaseFirestore _firestore;
Future<DocumentReference> addNewDocument(DocClass doc, ItemClass item,) {
Future<DocumentReference> result = _firestore
.collection('Documents')
.add(doc.toJson())
.collection(‘Items’) // I cannot do this without await and cannot use await while offline.
.add(item.toJson());
return result;
}
}
Solution
I think I figured it out with some help from another answered question on here. Obviously, I was doing it wrong… I changed the code to first generate a new DocumentReference and set its values from the map. This way I don’t have to await for the Future to return and will have the reference of the document to add to its subcollection. Now everything works as expected. Here’s the rewrite to the sample code:
Future<void> addNewDocument(
{@required DocClass doc,
@required ItemClass item}) {
final DocumentReference docRef = _firestore.collection(‘Documents’).doc();
doc.id = docRef.id;
_firestore.collection(‘Documents’).doc(doc.id).set(doc.toJson());
final DocumentReference itemRef = docRef.collection('Items').doc();
item.id = itemRef.id;
docRef
.collection(‘Items’)
.doc(item.id)
.set(item.toJson());
}
Answered By - Andrey Sorokin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.