Unable to return list of object from firebase Stream query

Viewed 161

I am making a firebase query which must return a list of object as stream.So to achieve that I am using Async* to wait for my loop for to complete before continueing the process. But the problem is that, my function stopped in If condition and does not enter inside his for loop and my function does not return anything. Yours helps would be welcome.

Here is my code

Stream<List<InfoCompagnie>> fetchCompanies(
    String depart, String arrivee, String jour, int place) async* {
  var q = await db.collection('DISPONIBILITE').snapshots();
  await for (var q1 in q) {
    for (var compagnies in q1.documents) {
      var NomCompagnie = compagnies.data[firstCaseDate];
      for (var compagnie in NomCompagnie) {
        await for (var q2 in qq) {
          if (q2.documents.isNotEmpty) {
            //Making condition here
            for (var data in q2.documents) {
              await compagnieList
                  .add(infoCompagnie.value); //add Object here into list
            } 
            yield compagnieList; //return stream data here
          }//Function stopped here
        }
      }
    }
  }
}
1 Answers

You should only await futures, not streams.

Here await is not necessary in most of your code, since db.collection('DISPONIBILITE').snapshots() returns a stream. And the rest of your code seems synchronous. Except for compagnieList.add(infoCompagnie.value), which is a future and requires await.

A Future represents a computation that doesn’t complete immediately. Where a normal function returns the result, an asynchronous function returns a Future, which will eventually contain the result. The future will tell you when the result is ready.

A stream is a sequence of asynchronous events. It is like an asynchronous Iterable—where, instead of getting the next event when you ask for it, "the stream tells you that there is an event when it is ready."

That last line also explains why you shouldn't wait on streams: the stream tells you that there is an event when it is ready.

source

Related