【问题标题】:Flutter Firebase – Retrieve array & map data?Flutter Firebase – 检索数组和地图数据?
【发布时间】:2021-12-07 10:05:08
【问题描述】:

我想从 Firestore 中检索数据并在我的 Flutter 应用程序中显示它们,但该文档有一个名为“用户”的地图,我的问题是如何访问此地图字段?

StreamBuilder(
    stream: FirebaseFirestore.instance
        .collection('Channels')
        .where('participants', arrayContains: UserInfoData.userID)
        .snapshots(),
    builder: (context, AsyncSnapshot<QuerySnapshot> streamSnapshot) {
      switch (streamSnapshot.connectionState) {
        case ConnectionState.waiting:
          return Center(
            child: CircularProgressIndicator(),
          );

        default:
          if (streamSnapshot.hasError) {
            print(streamSnapshot.hasError.toString());
          } else {
            final channels = streamSnapshot.data!.docs;
            if (channels.isEmpty) {
              return Text('ff');
            } else
              return ListView.builder(
                itemCount: channels.length,
                itemBuilder: (context, i) => ListTile(
                  leading: CircleAvatar(
                    backgroundImage:
                        NetworkImage(channels[i]['announceImage']),
                  ),
                  title: Text(channels[i]['reciverID']),
                ),
              );
          }
      }
      return Text('ok');
    },
  ),
);

【问题讨论】:

  • 访问其他属性的方式相同:channels[i]['announceImage'],所以您可以调用channels[i]['users'],对吗?但是你得到的是一个地图而不是一个字符串。
  • 是的,我有一张地图如何获取这样的数据?

标签: firebase flutter dart


【解决方案1】:

您可以在这里获取值,就像任何其他包含键的地图一样。在您的情况下,users 是一个包含键 lastname、name、userid 的映射。 channels[i]['users'] 将为您提供 users 地图。要获取特定键的值,您可以将 channels[i]['users'] 视为一个整体,就像一个数组。

因此,您可以通过执行以下操作来获取值:

字符串姓氏 = 频道[i]['users']['lastname']
字符串名称 = 频道[i]['users']['name']

【讨论】:

    猜你喜欢
    • 2021-08-04
    • 2020-07-07
    • 2020-01-15
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 2021-06-13
    • 2018-10-11
    • 2021-02-06
    相关资源
    最近更新 更多