【问题标题】:How to merge multiple streams inside a stream如何在一个流中合并多个流
【发布时间】:2019-04-02 12:48:45
【问题描述】:

我正在尝试使用标签栏和标签栏视图来显示火基地的一些元素。首先,我使用流生成器来获取标签栏中的标签文本:

class HomePage extends StatelessWidget {
final FirebaseUser user;


  HomePage({this.user});

  @override
  Widget build(BuildContext context) {
    return new StreamBuilder<QuerySnapshot>(
    stream: Firestore.instance.collection("places").snapshots(),
    builder: (BuildContext context,AsyncSnapshot<QuerySnapshot> snapshot){
        if (!snapshot.hasData){
        return Center(child: CircularProgressIndicator());
      }
      else{
      return DefaultTabController(
      length: 20,
      child: Scaffold(
      appBar: AppBar(
         title: Text("Home Page"),
         bottom: TabBar( isScrollable: true,
              tabs: new List.generate(snapshot.data.documents.length, (index) {
                     return new Tab(child: Text(snapshot.data.documents[index]['name'].toString().toUpperCase()));
              }),)),

然后我想从 fire 存储中获取一个名为“temps”的集合的流构建器,其中包含文档,每个文档 id 代表另一个名为“users”的集合中的文档 id。在用户的每个文档中,我都有一个名为 place 的字段。我已经制作了标签并且它可以工作但是,我不能做的是: 想要获取集合 temps 中每个文档的文档 ID,并获取此文档 ID 并使用它来访问“用户”集合中具有相同 ID 的文档,并检查字段位置是否与选项卡中名称的值相同栏我想出现在标签栏视图中! 我该怎么做?

【问题讨论】:

    标签: firebase flutter google-cloud-firestore stream


    【解决方案1】:

    如果我理解正确,一种解决方案是在其State 中创建一个StatefulWidget,使用本地StreamController 并将您的StreamBuilder 指向它。

    分别使用两个 Streams 并将这些项目添加到您的 StreamController。

    看起来有点像:

    class YourClass extends StatefulWidget {
      ... createState() ...
    }
    
    
    class _YourClassState extends State<YourClass> {
      StreamController<YourItem> _places;
    
      @override
      void initState() {
        super.initState();
    
        // the unified stream
        _places = new StreamController();
    
        // listening to changes of the first reference
        CollectionReference places1Ref = Firestore.instance.collection("places1");
        places1Ref.listen((snapshopt) {
          // posting item to the unified streamController
          _places.add(item);
        });
    
        // listening to changes of the second reference
        CollectionReference places2Ref = Firestore.instance.collection("places2");
        places2Ref.listen((snapshopt) {
          // posting item to the unified streamController
          _places.add(item);
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return StreamBuilder<YourItem>(
          stream: _places.stream, // using here only the unified stream
          builder: (context, snapshot) {
            return YourWidgets();
          }
        );
      }
    }
    

    此模型使用YourItem 作为统一对象,但您可以使用其他对象,包括dynamic 本身。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 2020-08-21
      • 1970-01-01
      • 1970-01-01
      • 2015-12-23
      相关资源
      最近更新 更多