Home > other >  Get one field from one document in Firestore
Get one field from one document in Firestore

Time:06-02

I want the username from the current logged in user in my flutter app.

This is what I have currently.

Future<String> get username async {
await FirebaseFirestore.instance
    .collection('users')
    .doc(user.uid)
    .get()
    .then((snapshot) {
  if (snapshot.exists) {
    return snapshot.data()!['username'].toString();
  }
});
return 'No User';
}

It's giving me "Instance of 'Future<String>'.

CodePudding user response:

Future<String> get username         async {
await         FirebaseFirestore.instance
.collection('users')
.doc(user.uid)
.get()
.then((snapshot) {
    if (snapshot.exists)
 { 
  _user = snapshot.data['username'].toString();         
    return _user    
}    
});
    return 'No User';
}

CodePudding user response:

That is expected. Since you're using an asynchronous operation inside he getter implementation and that takes time to complete, there is no way for it to return the string value right away. And since it's not possible to block the execution of the code (that would lead to a horrible user experience), all it can return now is Future<String>: an object that may result in a string at some point.

To get the value from a Future, you can either use then or await. The latter is easiest to read and would be:

print(await username);

With then() it's look like this:

username.then((value) {
  print(value); 
})

To learn more about dealing with asynchronous behavior in Flutter/Dart, check out Asynchronous programming: futures, async, await.

  • Related