【发布时间】:2021-07-16 11:33:44
【问题描述】:
伙计,将多个 Firebase 流合并到一个流是一个真正的问题。有人应该为此写一篇文章或一个简单的视频教程。使用 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 时,我收到了一批错误:
类“列表”没有实例获取器“文档”。 接收方:“_GrowableList”的实例(长度:2) 尝试调用:docs
请告诉我如何将这两个 firebase 流嵌套到 ome 中,或者如何使用 Rx.combineLatest2 方法来解决这个问题。
【问题讨论】:
-
问题是我不知道如何将多个流合并为一个流。我想我错过了一些东西。