【问题标题】:await Function does not return a valueawait 函数不返回值
【发布时间】:2021-05-06 23:01:06
【问题描述】:

我已经创建了函数get user并从firestore设置了它的数据,这是函数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;

  }

然后我有我的个人资料页面,我创建了将用户从 getUser() 设置为当前用户的函数,如下所示:

User me;
String myUID = "t4skPFRXcLPxAWvhHpaiPOfsrPI3";

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

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

但是当我尝试使用 print 例如 print(me.name) 没有任何事情发生时,当我尝试将 networkImage 的 url 设置为 me.profilePhoto 时出现错误,告诉我它的 url 为空。

【问题讨论】:

  • 这能回答你的问题吗? What is a Future and how do I use it?
  • @ChristopherMoore 我已经完成了您链接中的所有说明,但如果有什么事情我应该告诉我或者我做错了什么事情告诉我。

标签: flutter android-studio dart google-cloud-firestore


【解决方案1】:

不要混合使用 async-await 和 .then 语法。这是可以做到的,但它更可能是混淆而不是帮助。将 async 修饰符添加到您的函数没有任何作用,因为您的函数不使用 await。

考虑以下选项:

用.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);
      });
    });
  }

使用异步等待

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;

  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-23
    • 2019-03-01
    • 2021-08-06
    • 2021-03-15
    • 1970-01-01
    • 1970-01-01
    • 2020-07-14
    • 2019-11-23
    相关资源
    最近更新 更多