2

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

1
  • 1
    It looks like you're caught by a common misunderstanding about deferred execution. The return value from this function is null because the function doesn't return anything. It just assigns documentName to a future and returns. This function must return a Future<String> and the caller must await it. Commented Jan 18, 2020 at 15:42

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.