簡體   English   中英

在 flutter 中合並多個 firebase stream

[英]Merging multiple firebase stream in flutter

伙計,將多個 firebase 流合並到一個 stream 是一個真正的問題。 有人應該為此寫一篇文章或一個簡單的視頻教程。 使用 StreamGroup、FlatMap()、Rx.combineLatest、StreamZip 或 CombineLatestesStream。 我從昨天開始嘗試解決這個問題,但我無法得到明確的指導。

class CartPage extends StatefulWidget{
   @override
   _CartPageState createState() => _CartPageState();
}
class _CartPageState extends State<CartPage> {
   
   // a firebase collection for all items
   Stream stream1 = EcommerceApp.firestore
    .collection("items")
    .where("shortInfo",
        whereIn: EcommerceApp.sharedPreferences
            .getStringList(EcommerceApp.userCartList))
    .snapshots();

   // a firebase collection for flash sales items
   Stream stream2 = EcommerceApp.firestore
    .collection("flashitem")
    .where("shortInfo",
        whereIn: EcommerceApp.sharedPreferences
            .getStringList(EcommerceApp.userCartList))
    .snapshots();

   List<QuerySnapshot> getList(QuerySnapshot list1) {
   List<QuerySnapshot> result = [];
   (list1 as List).forEach((element) {
     result.add(element);
    });
     return result;
   }

 @override
 Widget build(BuildContext context) {

  Stream combineStream = Rx.combineLatest2(streamA, streamB, (a, b) => [a, b]);


   return Scaffold(
    appBar: MyAppBar(),
    body:CustomScrollView(
      slivers: [
        SliverToBoxAdapter(
          child: Container(
            height: 10.0,
          ),
        ),
       StreamBulder(
       stream: combineStream,
        builder: (context, snapshot) {
              if (!snapshot.hasData) {
                return SliverToBoxAdapter(
                  child: Center(
                    child: circularProgressBar(),
                  ),
                );
              } else {
              List<QuerySnapshot> _list = [];
                _list.addAll(getList(snapshot.data[0]));
                _list.addAll(getList(snapshot.data[1]));
                if (_list.length == 0) {
                } else {
                  return SliverList(
                    delegate: SliverChildBuilderDelegate(
                      (context, index) {
                        ProductModel model = ProductModel.fromJson(
                           _list[index].docs[index].data());

                        return cartSourceInfo(model, context,
                            removeCartFunction: () =>
                                removeItemFromUserCart(model.shortInfo));
                      },
                      childCount: childCount: snapshot.hasData ? _list.length : 0,
                    ),
                  );
                }
              }
            }    
       )
    );
 }
}

這里的大多數答案都是使用 rxdart 中已棄用的 Observable 庫,當我嘗試使用相同的語法來解決使用 Rx.latestCombine2 時,沒有數據流。 當我嘗試將 list 類型的 querySnapshot 傳遞給 stream Stream<List> 時,我收到了一批錯誤:

Class 'List' 沒有實例 getter 'docs'。 接收方:“_GrowableList”的實例(長度:2)嘗試調用:docs

請告訴我如何將這兩個 firebase stream 嵌套到 ome 中,或者如何使用 Rx.combineLatest2 方法來解決這個問題。

語法看起來是正確的,但是當嘗試訪問每個 stream 的數據時,您必須按索引訪問它,因為快照基本上是一個列表

所以要訪問stream1和stream2的快照,應該像這樣訪問

snapshot.data[0].docssnapshot.data[1].docs分別。

您可以結合兩個流並在 Ui 中顯示列表,並確保根據snapshot.data[index].docs的類型分配適當的類型T


 List<QuerySnapshot> combineLists(
      List<QuerySnapshot> list1, List<QuerySnapshot> list2) {
    List<QuerySnapshot> result = [];
    list1.forEach((element) {
      result.add(element);
    });
    list2.forEach((element) {
      result.add(element);
    });
    return result;
  }

StreamBulder(
 ​stream: combineStream,
 ​builder: (context, AsyncSnapshot<List<QuerySnapshot>> snapshot) {
   ​if (!snapshot.hasData) {
      ​return SliverToBoxAdapter(
        ​child: Center(
          ​child: circularProgressBar(),
          ​),
        ​);
      ​} else {​
         final List<QuerySnapshot> _list=[];
         final List<QuerySnapshot> combineSnapshot =
                    combineLists(snapshot.data[0], snapshot.data[1]);
         ​if (_list.length == 0) {
            ​return addItems();
         ​} else {
             return SliverList(
                ​delegate: SliverChildBuilderDelegate(
                (context, index) {
                     ProductModel model = ProductModel.fromJson(
                     _list[index].data());
                 return cartSourceInfo(model, context, removeCartFunction: 
                    () => removeItemFromUserCart(model.shortInfo));
                 ​},
                 childCount:_list.length,
                 ),
               );
           ​}
        }
   }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM