How can you nest StreamBuilders in Flutter?

前端 未结 2 1852
-上瘾入骨i
-上瘾入骨i 2021-01-07 00:16

I have 2 Streams that I need to combine to build a widget, but unlike other questions I have seen I need to nest my streams.

I have a stream that gets a collection

2条回答
  •  隐瞒了意图╮
    2021-01-07 00:50

    I have done something similar simply using nested StreamBuilders. Depending on how you want your Widgets organized, you can create streams within the outer StreamBuilder. Based on your clarifying comments, this is one possibility:

    @override
    Widget build(BuildContext context) {
    
      var habits = Firestore.instance
        .collection("users")
        .document('VtL1sxOoCOdJaOTT87IbMRwBe282')
        .collection("habits")
        .snapshots();
    
      return StreamBuilder(
        stream: habits,
        builder: (context, snapshot) {
    
          if (!snapshot.hasData)
            return Text("Loading habits...");
    
          return ListView(children: snapshot.data.documents.map((document) {
    
            var query = Firestore.instance
              .collection("users")
              .document('VtL1sxOoCOdJaOTT87IbMRwBe282')
              .collection("habits")
              .document(document.documentID)
              .collection("history")
              .where('day', isGreaterThanOrEqualTo: start)
              .where('day', isLessThanOrEqualTo: end)
              .snapshots();
    
            return StreamBuilder(
              stream: query,
              builder: (context, snapshot) {
    
                if (!snapshot.hasData) return Text("Loading...");
    
                // right here is where you need to put the widget that you
                // want to create for the history entries in snapshot.data...
                return Container();
              },
            );
          }).toList());
        },
      );
    }
    

提交回复
热议问题