【问题标题】:How to fetch data from Firestore and display them in Flutter?如何从 Firestore 获取数据并在 Flutter 中显示?
【发布时间】:2020-12-27 16:12:28
【问题描述】:

我是 Flutter 和 Firestore 的初学者。我在firestore中有一个集合,顺序如下: event->'一个用户特定的 id'->post->'a post id->'post details'。你可以看到这里Firestore1和这里Firestore2

当我尝试获取“postdetails”时,我得到的只是“DocumentSnapshot 的实例”,请参阅此处Response

我尝试了什么:

 getEvents() async {
setState(() {
  _isLoading = true;
});

DocumentSnapshot snapshot = await eventref
    .doc(uid)
    .collection('post')
    //.orderBy('Date', descending: true)
    .doc()
    .get();

print('Snapshot : ${snapshot}');
 return snapshot;
// setState(() {
//   _isLoading = false;

//   print(event);
// });

}

我还为事件做了一个模型。看这里Event Model

我想获取数据并将它们显示为卡片。 有什么帮助吗? 提前致谢

【问题讨论】:

    标签: flutter


    【解决方案1】:
    print('Snapshot : ${snapshot.data()["Date"]}');
    

    使用data() 可以访问字段值。

    【讨论】:

    • 它给出了错误:E/flutter (22875): 尝试调用:[]("Date") E/flutter (22875): #0 Object.noSuchMethod (dart:core-patch/object_patch. dart:51:5) E/flutter (22875): #1 _TimelineState.getEvents
    • 试试snapshot.data()
    【解决方案2】:
    snapshot.get("field_name")
    

    您需要让 Flutter 检索文档快照中的字段。

    需要更详细的 Firestore 集合和文档顺序,以提供准确的代码。您可以按照以下示例进行操作:

    在 Firestore 上:

    -Collection: "users"
    ---Document: "userId"
    -------Field: "username"
    -------Field: "birthdate"
    

    代码:

    DocumentSnapshot doc =await _firestore.collection("users").doc(userId).get();
    print(doc.get('username'));
    print(doc.get('birthdate'));
    

    【讨论】:

      猜你喜欢
      • 2020-05-11
      • 2019-02-26
      • 2021-11-28
      • 2018-11-12
      • 2021-07-17
      • 1970-01-01
      • 2020-10-01
      • 2019-07-26
      • 1970-01-01
      相关资源
      最近更新 更多