Get one field from one document in Firestore

Viewed 179

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>'.

3 Answers

Figured it out... ended up using this.

FutureBuilder<DocumentSnapshot<Map<String, dynamic>>>(
                  future: FirebaseFirestore.instance
                      .collection('users')
                      .doc(user.uid)
                      .get(),
                  builder: (_, snapshot) {
                    if (snapshot.hasData) {
                      var data = snapshot.data!.data();
                      var value = data!['username'];
                      return Text(value);
                    }
                    return const Text('User');
                  },
                ),
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';
}

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