【问题标题】:How to display a Map inside a field of a specific document in firestore using flutter?如何使用颤振在firestore中特定文档的字段内显示地图?
【发布时间】:2021-08-10 13:44:51
【问题描述】:

This is the structure你好,如何从firestore中检索特定文档字段内的地图以及如何在应用程序中将其显示为列表。这怎么可能实现?有人可以分享一个示例 sn-p 代码。例如在“Collection-Doc-Field-{key : value}”中,我想显示字段中的地图。

更新:

Expanded(
                child: new ListView(
                  children: snapshot.data
                      .get('$field')
                      .map((DocumentSnapshot document) {
                    return new ListTile(
                        title: Column(
                            children: (document.data()['$field']
                                    as Map<String, dynamic>)
                                .entries
                                .map((e) => ListTile(
                                    title: Text(e.key),
                                    trailing: Text(e.value.toString())))
                                .toList())
                        //subtitle: new Text(document.data()['Subjects']),
                        );
                  }).toList(),
                ),
              ),

这就是我尝试显示字段地图的方式,但最终出现此错误

The following _TypeError was thrown building StreamBuilder<DocumentSnapshot>(dirty, state: _StreamBuilderBaseState<DocumentSnapshot, AsyncSnapshot<DocumentSnapshot>>#d3cf2):
type '(DocumentSnapshot) => ListTile' is not a subtype of type '(String, dynamic) => MapEntry<dynamic, dynamic>' of 'transform'

【问题讨论】:

    标签: firebase flutter dart google-cloud-firestore


    【解决方案1】:

    在您的代码中,snapshot.data 是一个 DocumentSnapshot 对象。因此,当您调用.get(field) 时,它会根据您的数据库结构返回一个Map&lt;String, dynamic&gt; 对象。 当您编写 .map(DocumentSnapshot document) 时,您使用了错误的类型,因为它是为了映射 Map&lt;String, dynamic&gt; 中的项目,而不是 DocumentSnapshot 类型。

    解决方案

    您需要将 get('$field') [可以简化为 get(field)] 的结果转换为您期望的对象类型 [在这种情况下,它的类型为 Map&lt;String, dynamic&gt;] 然后循环通过每个地图条目返回一个ListTile 小部件。

    将您的代码更新为以下代码,这应该可以修复错误:

         return ListView(
           children:
             (snapshot.data.get(field) as Map<String, dynamic>)
               .entries
               .map((MapEntry mapEntry) {
                 return ListTile(
                   title: Text(mapEntry.key),
                   trailing: Text(mapEntry.value.toString()));
           }).toList(),
         );
    

    【讨论】:

    • 太棒了!它奏效了。但是 Victor 能否告诉我我的代码中的主要问题是什么。为什么使用 map 而不是 MapEntry 会导致该异常?
    • 嗨,@Learn,我已经用解释更新了我的答案。如果您需要更多解释,请告诉我。
    • 知道了!感谢您的解释
    猜你喜欢
    • 2021-08-11
    • 2020-10-23
    • 2021-08-11
    • 1970-01-01
    • 2020-08-05
    • 2019-01-09
    • 1970-01-01
    • 2022-01-21
    相关资源
    最近更新 更多