简体   繁体   中英

Get one field from one document in Firestore

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM