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));
Share:
339
DEFL
Author by

DEFL

Updated on December 28, 2022

Comments

  • DEFL
    DEFL over 1 year

    I have a Streambuilder that takes Firebase Firestore snapshot as a Stream and I would like to add initalData to the Streambuilder.

    How can I pass initalData to the Streambuilder?

    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
    DEFL about 3 years
    Thank 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
    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
    DEFL about 3 years
    The best way to get it right with the Type etc. would be to make a ModelClass right?
  • osaxma
    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 map QuerySnapshot to it. They are just different ways of doing the same thing..
  • DEFL
    DEFL about 3 years
    Ok thank you I am still learning and sometimes things are pretty difficult for me