2
votes

Im trying to return the length of a list of documents with this function:

Future totalLikes(postID) async {
    var respectsQuery = Firestore.instance
        .collection('respects')
        .where('postID', isEqualTo: postID);
      respectsQuery.getDocuments().then((data) {
      var totalEquals = data.documents.length;
      return totalEquals;
    });
  }

I'm initialize this in the void init state (with another function call:

void initState() {

    totalLikes(postID).then((result) {
      setState(() {
        _totalRespects = result;
      });
    });


  }

However, when this runs, it initially returns a null value since it doesn't have time to to fully complete. I have tried to out an "await" before the Firestore call within the Future function but get the compile error of "Await only futures."

Can anyone help me understand how I can wait for this function to fully return a non-null value before setting the state of "_totalRespsects"?

Thanks!

1

1 Answers

10
votes

I think you're looking for this:

Future totalLikes(postID) async {
  var respectsQuery = Firestore.instance
      .collection('respects')
      .where('postID', isEqualTo: postID);
  var querySnapshot = await respectsQuery.getDocuments();
  var totalEquals = querySnapshot.documents.length;
  return totalEquals;
}

Note that this loads all documents, just to determine the number of documents, which is incredibly wasteful (especially as you get more documents). Consider keeping a document where you maintain the count as a field, so that you only have to read a single document to get the count. See aggregation queries and distributed counters in the Firestore documentation.