【问题标题】:Not able to retrieve documents from firestore无法从 Firestore 中检索文档
【发布时间】:2020-08-31 00:56:33
【问题描述】:

我正在尝试从 firestore 中检索文档并将其存储到列表中,但我正在返回 [Instance of 'QueryDocumentSnapshot', Instance of 'QueryDocumentSnapshot']。此外,它不返回文档列表,但字段作为数组的长度仅为 2,但我在“组织”集合中有 6 个文档。我在 SO 上问过类似的问题,但没有得到正确的答案。

这是我为获取文档列表而实现的代码:

Future<List> getHistory() async {
  List history;

  final List<DocumentSnapshot> documents = 
      (await FirebaseFirestore.instance.collection("Org").get()).docs;

  history = documents.map((documentSnapshot) => documentSnapshot).toList();

  return history;
}
@override
  initState() {
    emailInputController = new TextEditingController();
    pwdInputController = new TextEditingController();
    setlist();
    super.initState();
    Firebase.initializeApp();
    
  }
   void setlist()async {
     List list = await getHistory();
    print(list)
   }

我想将“Org”集合中的所有文档存储在一个列表中。这是供参考的图片。

【问题讨论】:

    标签: firebase flutter google-cloud-firestore


    【解决方案1】:

    你好像忘记做某事了

    history = documents.map((documentSnapshot) => documentSnapshot).toList();
    

    在这里调用map 没有任何作用,因为您没有进行任何映射。您可能打算致电

    history = documents.map((documentSnapshot) => documentSnapshot.data()).toList();
    

    从每个快照中检索数据并将其映射到新列表。


    如果您想要文档 ID 而不是字段,请执行 .id 而不是检索数据:

    history = documents.map((documentSnapshot) => documentSnapshot.id).toList();
    

    【讨论】:

    • 太棒了!!它解决了实例问题,但它返回的是文档中的字段而不是文档列表
    • 有什么解决办法吗? @克里斯托弗·摩尔
    • @MrunalJoshi 请澄清问题。
    • 我已经更新了这个问题。希望它能澄清问题。
    • @MrunalJoshi 如果您有新问题,请不要编辑原始问题,在此处接受或创建答案并创建新问题。您在 Org 集合中只有 2 个文档。 Organisation 2 中不得有任何字段。
    猜你喜欢
    • 2020-10-30
    • 1970-01-01
    • 2021-11-18
    • 1970-01-01
    • 2018-05-13
    • 2021-09-23
    • 2019-01-25
    • 1970-01-01
    • 2019-04-26
    相关资源
    最近更新 更多