【问题标题】:Firestore Class 'QuerySnapshot' has no instance method '[]'Firestore 类“QuerySnapshot”没有实例方法“[]”
【发布时间】:2020-07-14 10:13:49
【问题描述】:

我想要一个 ListView 来显示用户的姓名。我正在使用带有 admin sdk 的 cloudfunction 来返回具有相应用户 ID 的所有用户的列表。当我想将该 uid 传递给带有流构建器的 Widget 时,它给了我错误:

Class 'QuerySnapshot' has no instance method '[]'.
Receiver: Instance of 'QuerySnapshot'
Tried calling: []("firstName")

这是我在为标题构建 ListView 时调用的函数:

Widget getFirstName(uid, item) {
  return StreamBuilder(
    stream: Firestore.instance
        .collection('users')
        .document('HzBUMs06BAPHK0Y7m5kfOmUzawC2')
        .collection('userInfo')
        .snapshots(),
    builder: (BuildContext context, AsyncSnapshot snapshot) {
      if (!snapshot.hasData) {
        return Text('${item['email']}');
      } else {
        return Text('${snapshot.data.documents['firstName']}');
      }
    },
  );
}

我还没有使用我将传递给它的 uid,因为我现在硬编码的用户 ID 是唯一一个包含 firstName 数据的用户 ID。

当我向它提供一个不存在的用户 ID 时,它似乎仍然认为其中有数据并尝试返回其(不存在的)数据。

我在这里做错了什么?

【问题讨论】:

  • 您应该使用 .exists 检查文档是否存在,如果不存在则跳过

标签: flutter google-cloud-firestore


【解决方案1】:

我设法通过使用这段代码来修复它:

Widget fullNameWidget(uid) {
  return FutureBuilder(
    future: fullName(uid),
    builder: (context, snapshot) {
      return Text('${snapshot.data}');
    },
  );
}

Future fullName(uid) async {
  return Firestore.instance
      .collection("users")
      .document('$uid')
      .collection("userInfo")
      .getDocuments()
      .then((querySnapshot) {
    print(querySnapshot.documents[0]['firstName']);
    if (querySnapshot == 'null') {
    } else {
      return '${querySnapshot.documents[0]['firstName']} ${querySnapshot.documents[0]['lastName']}';
    }
    // querySnapshot.documents.where((element) {
    //   print(element.documentID == 'firstName');
    // });
  });
}

【讨论】:

    猜你喜欢
    • 2020-04-11
    • 2021-05-04
    • 2020-10-21
    • 1970-01-01
    • 2020-04-07
    • 2022-06-15
    • 2021-03-01
    • 2021-04-18
    相关资源
    最近更新 更多