简体   繁体   中英

How to get Firestore Data by method in Flutter

I am trying to get users name but Flutter gives this error:

The body might complete normally, causing 'null' to be returned, but the return type is a potentially non-nullable type.
Try adding either a return or a throw statement at the end.

Method:

  String getUserNameFromUID(String uid) {

    FirebaseFirestore.instance
        .collection('users')
        .where('uid', isEqualTo: uid)
        .get()
        .then((QuerySnapshot querySnapshot) {
      querySnapshot.docs.forEach((doc) {
        return doc["name"];
      });

    });

  }

How can I solve my problem? if I add return 0 to end of the method it always gives 0.

It always gives 0.(I do not want 0, I want get user name from uid)

  String getUserNameFromUID(String uid) {

    FirebaseFirestore.instance
        .collection('users')
        .where('uid', isEqualTo: uid)
        .get()
        .then((QuerySnapshot querySnapshot) {
      querySnapshot.docs.forEach((doc) {
        return doc["name"];
      });

    });

return "0";

  }

First your function should return a Future<String> since it relies on firestore's get wich also returns a future. Also docs is a list, you have to return just one. The first one i guess. In the UI just use a FutureBuilder

 Future<String> getUserNameFromUID(String uid) async {

    final snapshot = await FirebaseFirestore.instance
        .collection('users')
        .where('uid', isEqualTo: uid)
        .get();
     return snapshot.docs.first['name'];

  }

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