小编典典

从Flutter中的Firestore查询单个文档(cloud_firestore插件)

flutter

我只想通过其ID 检索 单个文档的 数据。我的示例数据方法:

TESTID1 {
     'name': 'example', 
     'data': 'sample data',
}

是这样的:

Firestore.instance.document('TESTID1').get() => then(function(document) {
    print(document('name'));
}

但这似乎不是正确的语法。

我找不到 有关 在flutter(飞镖)中 查询firestore的任何详细文档,
因为firebase文档仅解决了本机WEB,iOS,Android等问题,而没有解决Flutter。cloud_firestore的文档也太短了。只有一个示例显示了如何将多个文档查询到流中,这不是我想要的。

有关缺少文档的相关问题:https :
//github.com/flutter/flutter/issues/14324

从单个文档中获取数据并不难。

更新:

Firestore.instance.collection('COLLECTION').document('ID')
.get().then((DocumentSnapshot) =>
      print(DocumentSnapshot.data['key'].toString());
);

不执行。


阅读 383

收藏
2020-08-13

共1个答案

小编典典

但这似乎不是正确的语法。

这是不正确的语法,因为您错过了collection()通话。您无法document()直接致电Firestore.instance。要解决此问题,您应该使用以下方法:

var document = await Firestore.instance.collection('COLLECTION_NAME').document('TESTID1');
document.get() => then(function(document) {
    print(document("name"));
});

或者以更简单的方式:

var document = await Firestore.instance.document('COLLECTION_NAME/TESTID1');
document.get() => then(function(document) {
    print(document("name"));
});

如果要实时获取数据,请使用以下代码:

Widget build(BuildContext context) {
  return new StreamBuilder(
      stream: Firestore.instance.collection('COLLECTION_NAME').document('TESTID1').snapshots(),
      builder: (context, snapshot) {
        if (!snapshot.hasData) {
          return new Text("Loading");
        }
        var userDocument = snapshot.data;
        return new Text(userDocument["name"]);
      }
  );
}

它还将帮助您将名称设置为文本视图。

2020-08-13