Flutter merge two firestore streams into a single stream

前端 未结 4 1931
半阙折子戏
半阙折子戏 2021-01-03 08:31

I simply want to perform an \'OR\' operation and get the both results of two queries into one stream.

Here\'s my code with a single stream

 StreamBui         


        
4条回答
  •  失恋的感觉
    2021-01-03 09:01

    This should work.

    //Change your streams here
        Stream> getData() {
            Stream stream1 = Firestore.instance.collection('list').where('id', isEqualTo: 'false').orderBy('timestamp').snapshots();
            Stream stream2 = Firestore.instance.collection('list').where('id', isEqualTo: 'true').orderBy('timestamp').snapshots();
            return StreamZip([stream1, stream2]);
          }
    
    
      @override
      Widget build(BuildContext context) {
        return new Scaffold(
          body: StreamBuilder(
              stream: getData(),
              builder: (BuildContext context, AsyncSnapshot> snapshot1) {
    
                List querySnapshotData =  snapshot1.data.toList();
    
                //copy document snapshots from second stream to first so querySnapshotData[0].documents will have all documents from both query snapshots
                querySnapshotData[0].documents.addAll(querySnapshotData[1].documents);
    
                if (querySnapshotData[0].documents.isEmpty)
                  return Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Center(
                        child: CircularProgressIndicator(),
                      )
                    ],
                  );
                if (querySnapshotData[0].documents.length == 0)
                  return const Center(
                    child: Text(
                      "Not Available",
                      style: TextStyle(fontSize: 30.0, color: Colors.grey),
                    ),
                  );
    
                return new ListView(
                    children: querySnapshotData[0].documents.map((DocumentSnapshot document){
                     // put your logic here. You will have access to document from both streams as "document" here
                      return new ListCard(document);
                    }).toList()
                );
              }
          ),
        );
      }
    

    Hope this helps!!!

提交回复
热议问题