简体   繁体   中英

How to switch firestore queries in stream builder in flutter?

I have 3 different queries to use on 3 different sets of conditions in StreamBuilder<QuerySnapshot> but not able to do so. Below is the code

Query query;
if (a==b){
query = Firestore.instance.collection('collection1');
}

else if (c==d){
query = Firestore.instance.collection('collection2');
}
else if (e==f){
query = Firestore.instance.collection('collection3');
}

Inside Widget Build

StreamBuilder<QuerySnapshot>(

    stream: query.snapshots(),
    builder: (context,snapshot){
      if (!snapshot.hasData){
        return Text("Loading");
      }

      return ListView.builder(
          itemCount: snapshot.data.documents.length,
          itemBuilder: (context, index){

            String names = snapshot.data.documents[index]['name'];
            List steps = List.castFrom(snapshot.data.documents[index]["steps"])




            return NameCard(names: names,steps: steps);

          });
    },

  )

I tried to implement the query with the stream builder, but not able to do so. if there is only one query it works perfectly fine. but when I tried to switch queries depending upon the conditions it does not work, it gives error of null snapshot

how should I achieve it??

Instead of

stream: query.snapshots()

Try defining the stream separately and then assign it to StreamBuilder.

Stream stream;

if (a==b){
    stream = Firestore.instance.collection('collection1').snapshots();
}
else if (c==d){
    stream = Firestore.instance.collection('collection2').snapshots();
}
else if (e==f){
    stream = Firestore.instance.collection('collection3').snapshots();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM