Reputation: 718
First of all, thank you so much for your time and help.
I have a method defined within a class to add data onto the Firestore database as shown below:
class DatabaseService {
Future<DocumentReference> addData() async {
DocumentReference doc = await _userCollection.add({
'firstName': 'Mickey',
'lastName': 'Mouse',
'age': 10,
'languages': ['English'],
'timestamp': FieldValue.serverTimestamp(),
});
return doc;
}
}
When I invoke this method on tap of a raised button, which is within a stateful class. It works perfectly fine as expected and creates a new document within the Firestore database. I would like the addData method to return the document ID of the newly created document, I'm not sure how to return and display the document ID.
This is how the code within my onPressed event looks:
onPressed: () {
Future<DocumentReference> doc =
DatabaseService().addData();
print(doc);
},
It just prints the following line in the console:
Instance of 'Future<DocumentReference>'
When I try printing the id property, it is giving me a compilation error.
print(doc.id);
I'm using the latest version of Firebase Firestore packages as listed below:
firebase_core: ^0.5.0
firebase: ^7.3.0
cloud_firestore: ^0.14.0+
Upvotes: 2
Views: 1253
Reputation: 2425
The reason you’re getting Instance of 'Future<DocumentReference>'
instead of the value is that it is a Future. Future need to be awaited before they have a value, or an error. You should have something like this instead
onPressed: () async {
DocumentReference doc = await DatabaseService().addData();
print(doc);
},
I strongly recommend you read more about asynchronous programming: futures, async, await. It will save you lots of headaches in the future, no pun intended :)
Upvotes: 2