对特定 Firestore 文档使用流构建 [英] Using Stream Building with a specific Firestore document

查看:27
本文介绍了对特定 Firestore 文档使用流构建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建 Flutter 应用程序,但在理解如何实施 Firestore 时遇到了问题.在我看过的教程中,我只看到了如何创建整个集合的快照,但是在我的情况下,我的集合是用户,所以我只需要对特定用户的文档进行快照.Firebase 文档上似乎没有关于如何执行此操作的文档,FlutterFire GitHub 页面上也没有太多文档.请帮忙!

I am building a Flutter application and I am having trouble understanding how to implement Firestore. Out of the tutorials I have seen, I only see how to create a snapshot of an entire collection, however in my case, my collection is users, so I only need to snapshot the document of a particular user. There doesn't appear to be documentation on the Firebase docs on how to do this nor is there much documentation on the FlutterFire GitHub page. Please help!

这是我尝试使用 StreamBuilder 构建的小部件.

This is the Widget I'm trying to build with StreamBuilder.

  @override
  Widget build(BuildContext context) {
    return new StreamBuilder(
      stream: Firestore.instance.collection('users').document(userId).snapshots(),
      builder: (context, snapshot) {
        return new ListView.builder(
          itemCount: //what do I put here?,
          itemBuilder: (context, index) => new Item(//And here?),
        );
      }
    );
  }

推荐答案

假设您想使用文档中的 name 参数创建一个 Text

Lets say you want to create a Text with the name parameter from your document

Widget build(BuildContext context) {
  String userId = "skdjfkasjdkfja";
  return StreamBuilder(
      stream: Firestore.instance.collection('users').document(userId).snapshots(),
      builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot) {
        if (!snapshot.hasData) {
          return Text("Loading");
        }
        var userDocument = snapshot.data;
        return Text(userDocument["name"]);
      }
  );
}

这只是一个例子.每次更改文档本身时,在文档上创建 StreamBuilder 都会重建自身.您可以尝试此代码,然后转到您的控制台并更改名称"价值.您的应用将自动反映更改.

This is just one instance. Creating a StreamBuilder on the document will rebuild itself every time the document itself is changed. You can try this code, and then go to your console and change the "name" value. Your app will automatically reflect the changes.

您可以构建使用流中数据的整个树,而不是仅使用一个 Text.

Instead of just one Text, you could build entire tree that uses data from your stream.

如果只想获取文档的当前值,可以通过解析文档引用的get()方法的Future来实现.>

If you want to get just at the moment value of the document, you can do so by resolving the Future of get() method on document reference.

var document = await Firestore.instance.collection('users').document(userId).get(),

这篇关于对特定 Firestore 文档使用流构建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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