I am trying to get the document id of my collection "blogs" in firebase . I tried to access it using id method but it is showing an error Cannot read properties of undefined (reading 'id')
.How can I access the document id?
this is how I tried to print the document id print(docRef.id);
but getting the error .What’s wrong with my code?
DocumentReference docRef =
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));
print(docRef.id);
titleController.clear();
myController.clear();
}
2
Answers
well, while you’re using
then
, try this instead :If you want to get the data after
FirebaseFirestore
method you need to use this approach instead of usingthen
method:when you use
then
to get anasync
value you only get that result insidethen
and can’t access it afterthen
.