LEAF
LEAF

Reputation: 39

Retrieve Document content from Firebase in Flutter

I'm trying to retrieve user data from a Firebase Collection.

This is what it looks like: Firebase

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

Answers (1)

Peter Haddad
Peter Haddad

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

Related Questions