简体   繁体   中英

Applying a boolean operator on FutureOr<bool> as part of fold

I am trying to check whether a boolean value in Firestore is true for a list of documents.

On trying to compile the code below I keep on getting the error The argument type 'Future<bool> Function(bool, DocumentReference<Object?>)' can't be assigned to parameter type 'FutureOr<bool>' .

Future<bool> checkValInAllDocsIstrue(
  List<DocumentReference> docs
) async {
  return docs.fold(Future.value(true),
    (Future<bool> acc, doc) => doc.get().then((doc_) {
      Map<String, dynamic> fetchDoc = doc_.data() as Map<String, dynamic>;
            bool val = fetchDoc["val"];
            return acc.then((acc_) => acc_ && val);
    }, onError: (e) => Future.error(e))
  );
}

Googling, I understand that acc_ && val is cast to FutureOr<bool> , but I have no idea how to cast this to the required Future<bool> . Any help would be appreciated.

Unfortunately, I cannot change the signature of the function as this is a given.

I noticed that it works if I explicitly cast the return type as follows (with an additional code cleanup),

Future<bool> checkValInAllDocsIstrue(
  List<DocumentReference> docs
) async {
  return docs.fold(true,
    (bool acc, doc) => doc.get().then((doc_) =>
       acc && doc_.data()["val"], onError: (e) => Future.error(e))
  ) as bool;
}

I hope this helps other people.

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