Unable to return list of object from firebase Stream query
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.
Siegfried Mabantey
Updated on December 23, 2022Comments
-
Siegfried Mabantey over 1 year
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 loopfor
to complete before continueing the process. But the problem is that, my function stopped inIf
condition and does not enter inside hisfor
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 } } } } }
-
Jan Hernandez over 3 yearsif you removed the
if
sentence, your code works fine? -
Siegfried Mabantey over 3 yearsNo @J.A.Hernández it trows me an error because we can not itterate from an empty document.
-
lenz over 3 yearsYou dont need to await a stream, only futures. Im fact, you might not need await at all here
-
Siegfried Mabantey over 3 yearsYes @lenz after removing the await keyword it works.Thanks
-
lenz over 3 yearsAh, fantastic! Ill write an answer then. Accept it if you can. Au plaisir! :) Je te souhaite beaucoup de succes avec ton projet
-
Siegfried Mabantey over 3 yearsMerci bien @lenz it is helpful.
-