在 Flutter 中从 Firestore 查询单个文档(cloud_firestore 插件) [英] Query a single document from Firestore in Flutter (cloud_firestore Plugin)

查看:29
本文介绍了在 Flutter 中从 Firestore 查询单个文档(cloud_firestore 插件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to retrieve data of only a single document via its ID. My approach with example data of:

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

是这样的:

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

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

but that does not seem to be correct syntax.

我无法在 flutter (dart) 中找到任何关于查询 firestore 的详细文档,因为 firebase 文档仅针对 Native WEB、iOS、Android 等,而没有针对 Flutter.cloud_firestore 的文档也太短了.只有一个示例展示了如何将多个文档查询到一个流中,这不是我想要做的.

I was not able to find any detailed documentation on querying firestore within flutter (dart) since the firebase documentation only addresses Native WEB, iOS, Android etc. but not Flutter. The documentation of cloud_firestore is also way too short. There is only one example that shows how to query multiple documents into a stream which is not what i want to do.

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

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

It can't be that hard to get data from a single document.

更新:

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().为了解决这个问题,你应该使用这样的东西:

It is not the correct syntax because you are missing a collection() call. You cannot call document() directly on your Firestore.instance. To solve this, you should use something like this:

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

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

If you want to get data in realtime, please use the following code:

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

它还可以帮助您将名称设置为文本视图.

It will help you set also the name to a text view.

这篇关于在 Flutter 中从 Firestore 查询单个文档(cloud_firestore 插件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆