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

查看:130
本文介绍了从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.

我找不到有关查询firestore的任何详细文档由于Firebase文档仅针对本机WEB,iOS,Android等,但不适用于Flutter,因此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

Related issue on missing documentation: 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()。要解决此问题,您应该使用类似以下的方法:

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天全站免登陆