【问题标题】:How to access multiple streams inside a StreamBuilder?如何访问 StreamBuilder 中的多个流?
【发布时间】:2018-12-04 14:24:28
【问题描述】:

我尝试在我的初始流的构建器中创建一个新的StreamBuilder,虽然我没有收到任何错误,但它似乎也不起作用。这可以吗?

基本上,我正在访问 Firebase 中的根集合。这个集合包含两个文档,我需要来自每个文档的数据,因为我正在构建一个包含来自两个路径的信息的 DataTable。

编辑:嵌套的 StreamBuilder 不起作用,因为 StreamBuilder 必须返回一个小部件,所以至少我知道它为什么不起作用。但是我仍然没有决定要做什么。

【问题讨论】:

  • 您可以通过多种方式组合流。 rxdart 包为此提供了大量的流转换器,来自 Dart 团队的 async 也提供了一些。
  • 您可以使用 StreamZip 或 StreamGroup 结合使用 .asBroadcastStream() 的组合流

标签: flutter stream-builder


【解决方案1】:

您是否尝试过使用StreamZip?这应该可以帮助您管理多个流。这是一个关于如何使用它的示例。

import 'package:async/async.dart';

Stream<DocumentSnapshot> stream1 = firestore.document('/path1').snapshots();
Stream<DocumentSnapshot> stream2 = firestore.document('/path2').snapshots();
StreamZip bothStreams = StreamZip([stream1, stream2]);

// To use stream
bothStreams.listen((snaps) {
 DocumentSnapshot snapshot1 = snaps[0];
 DocumentSnapshot snapshot2 = snaps[1];

 // ...
});

您是否有minimal repro 说明您尝试实施的内容以及复制行为的步骤?我还需要您尝试访问的数据的外观。这将帮助我想象您是如何尝试为 Firestore 运行多个流的(我假设因为提到了 Collection)。

【讨论】:

    【解决方案2】:

    你可以这样使用它:

        StreamBuilder(
            stream: firestore.collection("nameofcollection").doc.snapshots(),
            buider: (context, AsyncSnapshot snapshot){
                if(snapshot.hasError) return Text('your error');
                    if(snapshot.hasData){  
                        typeList List nameList = [];
                        snapshot.forEach((e){
                            typeObject object = ();
                            object.property1 = e.get('property1Database');
                            object.property2 = e.get('property2Database');
                            nameList.add(object);
                        });
                        //now use the list that will be loaded with the 2 documents
                     }
                }
        );
    

    【讨论】:

    • 行内 snapshot.forEach((e){ ,阅读 snapshot.doc.forEach((e){
    猜你喜欢
    • 2020-12-19
    • 2019-11-20
    • 1970-01-01
    • 1970-01-01
    • 2019-12-06
    • 2020-08-31
    • 2023-03-18
    • 2021-02-21
    • 1970-01-01
    相关资源
    最近更新 更多