Reputation: 39
I'm trying to retrieve user data from a Firebase Collection.
This is the method I wrote to get the data:
static String getUserData(creatorId, keyword) {
var documentName = Firestore.instance
.collection('users')
.document(creatorId)
.get()
.then((DocumentSnapshot) {
String data = (DocumentSnapshot.data['$keyword'].toString());
return data;
});
}
The method only returns null. If I print the String in the Method it works. How can I return the String?
Help would be greatly appreciated.
Cheers Paul
Upvotes: 2
Views: 94
Reputation: 80904
You need to use async
and await
to be able to wait for the data to be fully retrieved and then you can return the data.
The async and await keywords provide a declarative way to define asynchronous functions and use their results.
For example:
Future<String> getUserData(creatorId, keyword) async {
var documentName = await Firestore.instance
.collection('users')
.document(creatorId)
.get()
.then((DocumentSnapshot) {
String data = (DocumentSnapshot.data['$keyword'].toString());
return data;
});
}
And then you since getUserData
returns a Future
, you can use the await
keyword to call it:
await getUserData(id, key);
https://dart.dev/codelabs/async-await#working-with-futures-async-and-await
Upvotes: 2