异步功能:未来<查询快照>扑扑扑?

时间:2020-06-25 18:33:57

标签: firebase flutter dart async-await future

我在这里有这段代码:如果用户存在于数据库中,并且紧随其后的是CurrentUser,则会构建一个“取消关注”自定义按钮,否则它将构建一个关注按钮

CustomButton follow = CustomButton("Follow", Colors.red, Colors.red, Colors.white, user);
CustomButton unfollow = CustomButton("Unfollow", Colors.black, Colors.black, Colors.white, user);

AvatarHeader(user.username, " ", user.photoURL, checkIfFollowing(user.id)== true ? unfollow : follow)

checkIfFollowing()函数始终被评估为false,可能是因为我在此异步函数中遇到问题,该函数未返回布尔值

  checkIfFollowing(String fetchedUser) async{
    DocumentSnapshot doc = await FOLLOWERS
        .document(fetchedUser)
        .collection('userFollowers')
        .document(CURRENTUSER.id)
        .get()

      return doc.exists;
  }

我该如何解决?

编辑

  search(String query) {
    Future<QuerySnapshot> users = USERS
        .where("username", isGreaterThanOrEqualTo: query)
        .getDocuments();

        print(query);
        print("");
        onStringChange(users);

  }


FutureBuilder buildResults(){
    return FutureBuilder (
            future: results,
            builder: (context, snapshot) {
              if (!snapshot.hasData) {
                print("i dont have data");
                return circularProgress();
              }
              List<AvatarHeader> searchResults = [];
              snapshot.data.documents.forEach((doc) async {
                User user = User.fromDocument(doc);
                if (user.photoURL != null) {
                  print(user.username);
                  bool check = await checkIfFollowing(user.id);                  
                  CustomButton follow = CustomButton("Follow", Colors.red, Colors.red, Colors.white, user);
                  CustomButton unfollow = CustomButton("Unfollow", Colors.black, Colors.black, Colors.white, user);
                  searchResults.add(AvatarHeader(user.username, " ", user.photoURL, check == true ? unfollow : follow));
                }
              });
              return ListView(
                shrinkWrap: true,
                physics: ClampingScrollPhysics(),
                children: searchResults,
              );
            },
          );
  }

1 个答案:

答案 0 :(得分:1)

您需要在异步函数中返回一个Future,在您的特殊情况下,您需要一个Future<bool>

Future<bool> checkIfFollowing(String fetchedUser) async{
  DocumentSnapshot doc = await FOLLOWERS
    .document(fetchedUser)
    .collection('userFollowers')
    .document(CURRENTUSER.id)
    .get()

   return doc.exists;
}

我建议您看看Asynchronous programming: futures, async, await

Future(小写字母“ f”)是Future(大写的“ F”)类的实例。未来表示异步操作的结果,可以有两种状态:未完成或已完成。

编辑

如果没有更多细节,很难确定如何解决您的特定问题。如果我理解正确,则需要与此保持一致

FutureBuilder buildResults() {
  return FutureBuilder(
    future: results,
    builder: (context, snapshot) {
      if (!snapshot.hasData) {
        print("i dont have data");
        return circularProgress();
      }

      // get documents where user.photoURL != null
      var docsWhereUserPhotoIsNotNull = getDocumentsWithUserPhotoNotNull(snapshot.data.documents);

      // build a list of FutureBuilders
      return ListView.builder(
          shrinkWrap: true,
          physics: ClampingScrollPhysics(), 
          itemCount: docsWhereUserPhotoIsNotNull.length,
          itemBuilder: (context, index) {
            var doc = docsWhereUserPhotoIsNotNull[index];
            var user = User.fromDocument(doc);

            return FutureBuilder(
                future: checkIfFollowing(user.id),
                builder: (context, snapshot) {
                  if (!snapshot.hasData) {
                    return circularProgress();
                  }

                  bool check = snapshot.data;
                  CustomButton follow = CustomButton("Follow", Colors.red, Colors.red, Colors.white, user);
                  CustomButton unfollow = CustomButton(
                      "Unfollow", Colors.black, Colors.black, Colors.white, user);
                  return AvatarHeader(user.username, " ", user.photoURL, check == true ? unfollow : follow);
                });
          });
    }
  );
}

哪里

List<DocumentSnapshot> getDocumentsWithUserPhotoNotNull(List<DocumentSnapshot> documents) {
   var documentsWithUserPhotoNotNull = List<DocumentSnapshot>();

   documents.forEach((doc) async {
     User user = User.fromDocument(doc);
     if (user.photoURL != null) {
       documentsWithUserPhotoNotNull.add(doc);
     }
   });

   return documentsWithUserPhotoNotNull;
 }