异步函数:Future<Query Snapshot> 到 Flutter 中的 Bool?

Async Functions: Future<Query Snapshot> to Bool in Flutter?

我这里有这段代码:如果用户存在于数据库中并且它后面跟着 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 可能是因为我在这个 asyncronus 函数中遇到问题,它没有 return 布尔值

  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,
              );
            },
          );
  }

您需要 return 异步函数中的 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

A future (lower case “f”) is an instance of the Future (capitalized “F”) class. A future represents the result of an asynchronous operation, and can have two states: uncompleted or completed.

编辑

没有更多详细信息,很难确定如何解决您的具体问题。如果我没理解错的话,你需要有符合这个的东西

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;
 }