【问题标题】:Getting data from multiple sources in ListView.builder - Flutter在 ListView.builder 中从多个来源获取数据 - Flutter
【发布时间】:2019-02-05 15:52:41
【问题描述】:

我正在使用 ListView.builder 构造函数通过从 Firestore 检索数据来构建列表。

我有两个集合,在这些集合下我有不同文档中的数据。

收集消息:

  • 消息
    • 消息1
    • 消息2

message 中的每个文档都有以下键:msgBody、sender。 我将发件人 id 存储在消息文档的发件人字段中,这实际上是集合 Users 中各个用户的文档名称。

收藏用户:

  • 用户
    • 詹姆斯
    • 格雷格

我目前正在使用以下代码来读取消息集合并获取其中的文档,然后我在发件人字段中获取值并创建对相应发件人文档的文​​档引用并尝试使用用户获取发件人详细信息记录并使用我列表中的数据。

child: StreamBuilder<QuerySnapshot>(
                      stream: Firestore.instance.collection('Messages').snapshots(),
                      builder: (BuildContext context, AsyncSnapshot snapshot) {
                        if (!snapshot.hasData) return Center(child: CircularProgressIndicator());
                          return new ListView.builder(
                          itemCount: snapshot.data.documents.length,
                          padding: const EdgeInsets.all(6.0),
                          itemBuilder: (context, index) {
                            DocumentSnapshot ds = snapshot.data.documents[index];  
                            DocumentReference tRef = Firestore.instance.document('/users/'+ds['sender']);
                            DocumentSnapshot tRefD;
                            tRef.get().then((tData){
                              print(tData.data); // I can see the sender data in the console here
                              tRefD = tData;
                            });

                             if (ds.data.isNotEmpty)
                             {
                              return Column(
                               children: <Widget>[
                                  Text(ds['sender']), 
                                  Text(tRefD['name']), //App crashes here works when I comment this line
                                ],
                              );
                           } 
                          }
          )

如何从不同集合下的不同文档中读取数据,并在同一个ListView.builder中使用?

任何帮助将不胜感激:)

【问题讨论】:

    标签: dart flutter


    【解决方案1】:

    在获取您的用户名时,用户界面已经构建完毕。您需要为每个文档嵌套一个 FutureBuilderStreamBuilder。或者在单独的方法中调用 async,在 initState 中调用此方法并填充相应的字段,然后将它们加载到 build 方法中的 UI 中。

    【讨论】:

    • 感谢您的回复,我正在考虑使用嵌套 StreamBuilder 方法。你能举个例子说明如何在 StreamBuilder 中使用嵌套的 StreamBuilder 吗?
    • 直截了当,第一个 StreamBuilder 会返回另一个带有 Firestore.instance.document('/users/'+ds['sender']).asStream 的 StreamBuilder,然后构建你的 ListView
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 2021-02-03
    相关资源
    最近更新 更多