Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Firestore: FirestoreBuilder with initial data

I'm making my first Flutter app and I encounter a problem and doesn't found any solution for it.

I have a view where I render a Firestore document, and there is two ways of getting there:

  • From a list where I already loaded my documents
  • From Dynamic Links with uid attached as arguments (args)

So in order to listen document changes and loading the data when arriving from the link I used FirestoreBuilder like this:

    return FirestoreBuilder<EventDocumentSnapshot>(
        ref: eventsRef.doc(args.uid),
        builder: (context, AsyncSnapshot<EventDocumentSnapshot> snapshot, Widget? child) {
          if (!snapshot.hasData) {
            return Container();
          }
          Event? event = snapshot.requireData.data;
          
          return Scafold(); //Rest of my rendering code
        }
     );
       
 

How I could avoid first call to Firebase when I already have the data but still listen to changes? The main problem is that my hero animation doesn't work because of this.

I tried with a StreamBuilder and initialDataparam but since it's expecting stream I didn't know how to cast my data.

like image 411
Floran Avatar asked Feb 20 '26 01:02

Floran


1 Answers

Okay, so I found the solution myself after many tries, so I added my Model object that can be null as initialData, but the thing that makes me struggle with is how you get the data in the builder. You have to call different methods depending on where the data is coming from.

    return StreamBuilder(
        initialData: args.event
        ref: eventsRef.doc(args.uid),
        builder: (context, AsyncSnapshot<dynamic> snapshot) {
          // Here is the trick, when data is coming from initialData you only
          // need to call requireData to get your Model
          Event event = snapshot.requireData is EventDocumentSnapshot ? snapshot.requireData.data : snapshot.requireData;
          
          return Scafold(); //Rest of my rendering code
        }
     );
like image 200
Floran Avatar answered Feb 22 '26 23:02

Floran