Abdullrahman Wasfi
Abdullrahman Wasfi

Reputation: 501

await Function does not return a value

I have created function get user and set it's data from firestore, this is the code of function getUser.

  Future<User> getUser(String uid) async{
    User user;
    _firestore
        .collection(USERS_COLLECTION)
        .where("uid", isEqualTo: uid.toString())
        .getDocuments()
        .then((doc) {
      _firestore
          .document('/$USERS_COLLECTION/${doc.documents[0].documentID}')
          .get()
          .then((userData) {

        user = User(
          name: userData.data["name"],
          username: userData.data["username"],
          profilePhoto: userData.data["profilePic"],
        );


      }).catchError((e) {
        print(e);
      });
    });

    return user;

  }

Then I have my profile page I have created function to set user from getUser() to current user like this:

User me;
String myUID = "t4skPFRXcLPxAWvhHpaiPOfsrPI3";

    @override
      void initState() {
        super.initState();
        setUser();
      }
         ......

Future<void> setUser() async{
    me = await userManagment.getUser(myUID);
  }

But when I try to use print for example print(me.name) does not anything happen, when I try to set url of networkImage to me.profilePhoto there is an error showing tell me the url it's null.

Upvotes: 0

Views: 423

Answers (1)

Christopher Moore
Christopher Moore

Reputation: 17123

Don't mix async-await and .then syntax. It's something that can be done, but it will more likely confuse than help. Adding the async modifier to your function is doing nothing since your function does not use await.

Consider the following options:

With .then

Future<User> getUser(String uid) {
    return _firestore
        .collection(USERS_COLLECTION)
        .where("uid", isEqualTo: uid.toString())
        .getDocuments()
        .then((doc) {
      return _firestore
          .document('/$USERS_COLLECTION/${doc.documents[0].documentID}')
          .get()
          .then((userData) {

        return User(
          name: userData.data["name"],
          username: userData.data["username"],
          profilePhoto: userData.data["profilePic"],
        );


      }).catchError((e) {
        print(e);
      });
    });
  }

With async-await

Future<User> getUser(String uid) async{
    User user;

    try{
    var doc = await _firestore
        .collection(USERS_COLLECTION)
        .where("uid", isEqualTo: uid.toString())
        .getDocuments();
    
    var userData = await _firestore
          .document('/$USERS_COLLECTION/${doc.documents[0].documentID}')
          .get();

    user = User(
          name: userData.data["name"],
          username: userData.data["username"],
          profilePhoto: userData.data["profilePic"],
        );
    }
    catch(e) {
      print(e);
    }
    return user;

  }

Upvotes: 1

Related Questions