firebase - Flutter 中从 Firestore 查询单个文档(cloud_fires

编辑:这个问题已经过时了,我敢肯定,新的文档和最新的答案是现在可用的。

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

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

是这样的:

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

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

我无法在 Flutter (dart) 中找到关于查询 firestore 的任何详细文档,因为 firebase 文档仅涉及 Native 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());
);

不执行。

最佳答案

but that does not seem to be correct syntax.

这不是正确的语法,因为您缺少 collection() 调用。您不能直接在 Firestore.instance 上调用 document()。为了解决这个问题,你应该使用这样的东西:

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"]);
      }
  );
}

它还可以帮助您将名称设置为 TextView 。

关于firebase - Flutter 中从 Firestore 查询单个文档(cloud_firestore 插件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53517382/

相关文章:

dart - flutter 位置固定等效

android - flutter 意外退出

flutter - 如何将抽屉小部件放在右侧

firebase - 使用 Flutter 向 Cloud Firestore 添加对象

dart - 错误 : The name 'Image' is defined in the lib

flutter - 在 float 操作按钮上的 onPressed 回调中从脚手架显示 snack

dart - Flutter - 我正在寻找一种制作脉冲动画的方法

dart - Flutter 中带有调整下拉箭头图标的全宽 DropdownButton

dart - Flutter:右溢出 200 像素

dart - 如何在 Flutter 中更改 TextFormField 输入文本颜色