Flutter give Streambuilder initalData
339
You can add initialData
to StreamBuilder
:
StreamBuilder(
initialData: ..... // <~~~ add it here.
stream: ...
builder: ...
You just need to make sure that your initialData
matches that type of data coming from the stream. Since QuerySnapshot
is a Firebase specific type, you should map your stream to a data type that you can create and that's known to you.
Here's a pseudo code:
initialData: [MyDataType()],
stream: FirebaseFirestore.instance
.collection("events")
.snapshots().map((snapshot) => MyDataType.fromMap(snapshot.doc));
Author by
DEFL
Updated on December 28, 2022Comments
-
DEFL over 1 year
I have a
Streambuilder
that takes Firebase Firestore snapshot as a Stream and I would like to addinitalData
to theStreambuilder
.How can I pass
initalData
to theStreambuilder
?The Code:
StreamBuilder( stream: FirebaseFirestore.instance .collection("events") .snapshots(), builder: (BuildContext ctx, AsyncSnapshot<QuerySnapshot> snapshot) { if (!snapshot.hasData || snapshot.data.docs.isEmpty) { return NoDataRelatedLocation(); } if (snapshot.hasError) { return Text(snapshot.error.toString()); } else { return new RelatedLocationListing( relatedLocationList: snapshot.data.docs, ); } }, ),
-
DEFL about 3 yearsThank you that was actually the part I was stuck with I didn't know what Type I should give the initalData but I hope I am able to do it with your Instruction
-
osaxma about 3 years@EnviroApps to make sure you get the type right, assign it to stream builder such in
StreamBuilder<List<MyType>>
, so Dart analyzer can check that your mapping is correct. (btw, I'm just assuming here it's a List of MyType for example) -
DEFL about 3 yearsThe best way to get it right with the Type etc. would be to make a ModelClass right?
-
osaxma about 3 years@EnviroApps you can do that but also you can use
RelatedLocationListing
constructor directly when you map the snapshots as long as you can create that type for initialData and you can mapQuerySnapshot
to it. They are just different ways of doing the same thing.. -
DEFL about 3 yearsOk thank you I am still learning and sometimes things are pretty difficult for me