I am working on a Flutter app connected to Firebase Cloud Firestore and Storage, and I want to create documents in Cloud Firestore that contain the downloadURL of files in Storage. However, I also need the filename to be the unique ID of the same Firestore document. Right now I upload the file after I create the document, but it would cost me an extra write to update the Firestore document afterwards.
I want to prevent this. It might work if I could access the id of the newly created document within the add() function, so that I can pass it to the storageTask, which would return the downloadURL directly inside the add() function. Another option would be if I could create a document, get its ID, then do the upload task, and write all the data afterwards, but I''m not sure if this would count as one write or two, nor do I know how to create a document without setting any data.
What I have now is roughly like this:
CollectionReference activities = FirebaseFirestore.instance.collection('activities');
activities.add({
'postDate': DateTime.now(),
}).then((value) => _startUpload(id: value.id));
Where _startUpload
is a function that uploads a file to Storage, and could potentially return a downloadURL. I want to be able to access that URL in the add function like this:
CollectionReference activities = FirebaseFirestore.instance.collection('activities');
activities.add({
'postDate': DateTime.now(),
'downloadURL': _startUpload(id: SomehowGetThisDocuments.id)
});