In my blogapp ,I am trying to implement comment system in flutter using cloud firestore. Each document is a post and I am trying to add comments as a subcollection to each document. How can I access each document id so that I can access the subcollection ?
Here I tried to print the document id below but it shows error NoSuchMethodError: 'id' method not found Receiver: null Arguments: []
:
final ref = await FirebaseFirestore.instance
.collection('blogs')
.add({
'title': titleController.text,
'body': myController.text,
'author': name,
'date': DateFormat('dd/MM/yyyy,hh:mm')
.format(DateTime.now()),
})
.then((value) => successAlert(context))
.catchError((error) =>
errorAlert(context));
titleController.clear();
myController.clear();
print(ref.id);
}
This is my firestore database :
2
Answers
You need to have access to the document id inside blogs, and access it’s collection and the add your data like this…
When you dont have the document id Firebase provides the get() command which returns the content of a collection. Like this:
But i realize that you will need the document id, so to get this you have to store the id after inserting a post, i’ve an example from a personal project:
Now you can use the document id to update the post with a new comment, like this. For more information we have the Firestore documentation with flutter code snipets.