dartdart-async

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.


Solution

  • 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.