Firestore 集合查询作为 Flutter 中的流 [英] Firestore collection query as stream in flutter

查看:17
本文介绍了Firestore 集合查询作为 Flutter 中的流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从一个集合中查询一些文档,这个查询应该监听在被查询文档中所做的更改,所以我需要一个流.我正在关注(在 Dart/Flutter 中)

I'm trying to query a few documents from a collection, this query should listen to changes made in the queried documents, so I'd need a stream. I'm doing following (in Dart/Flutter)

  Stream<List<MatchRequest>> _getNewMatches() {
    return Collection<MatchRequest>(path: 'requests')
        .ref
        .where('status', isNull: true)
        .where('users', arrayContains: ['$currentUid'])
        .orderBy('last_activity')
        .snapshots()
        .map((list) => list.documents.map(
            (doc) => Global.models[MatchRequest](doc.data) as MatchRequest));
  }

(对象 Collection 在它的构造函数中设置 ref 的路径,例如:ref = db.collection($path) 并且地图制作结果模型)

然后我使用 StreamBuilder 和 stream 调用上面的方法和 builder 检查是否 snapshot.hasData.但它一直在加载,snapshot.hasData 一直是假的.我在这里做错了什么?

Then I'm using a StreamBuilder with stream invoking the method above and builder checking if snapshot.hasData. But it keeps loading, snapshot.hasData keeps being false. What am I doing wrong here?

  1. 我的 Firestore 安全规则包含:

  1. My firestore security rules contain:

match /requests/{requestId} {
    allow read: if isLoggedIn();
    allow write: if isLoggedIn();
}

  • 当删除每个 whereorderBy 时,它也找不到任何东西.并且请求集合中存在文档

  • When removing every where and orderBy, it doesn't find anything as well. And there are documents present in the requests-collection

    当试图从请求集合中仅查询 1 个文档作为流时,他确实找到了结果

    When trying to query only 1 document as a stream from the requests-collection, he does find the result

    是不是因为我应该向我的 Firestore 索引添加索引?但这并不能解决我的第一个问题,即即使没有 whereorderBy,它也不会获取任何数据

    Is it because I should add indexes to my firestore indexes? But this won't solve my first problem which is that even without where and orderBy, it doesn't get any data

    推荐答案

    我写了一个简单的例子,它看起来就像你正在尝试做但缺少 listen() 方法:

    I've written a simple example of it seems to be like what you are trying to do but are missing the listen() method:

    Firestore.instance.collection('collection')
      .where('field', isEqualTo: 'value')
      .orderBy('field')
      .snapshots()
      .listen((QuerySnapshot querySnapshot){
        querySnapshot.documents.forEach((document) => print(document));
      }
    );
    

    这只是如何从 Firestore Stream 获取数据并在 StreamBuilder 上使用它的示例:

    This is just an example of how you can take the data from a Firestore Stream and use it on a StreamBuilder:

    class _MyHomePageState extends State<MyHomePage> {
      Stream dataList;
    
      @override
      void initState() {
        dataList = Firestore.instance.collection('collection')
          .where('field', isEqualTo: 'value')
          .orderBy('field')
          .snapshots();
    
        super.initState();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text(widget.title),
          ),
          body: Center(
            child: StreamBuilder(
              stream: dataList,
              builder: (context, asyncSnapshot) {
                if(asyncSnapshot.hasError)
                  return Text('Error: ${asyncSnapshot.error}');
    
                switch (asyncSnapshot.connectionState) {
                  case ConnectionState.none: return Text('No data');
                  case ConnectionState.waiting: return Text('Awaiting...');
                  case ConnectionState.active:
                    return ListView(
                      children: asyncSnapshot.data.map((document) => Text(document['value'])),
                    );
                  break;
                  case ConnectionState.done: return ListView(
                    children: asyncSnapshot.data.map((document) => Text(document['value'])),
                  );
                  break;
                }
                return null;
            }),
          ),
        );
      }
    
    } 
    

    这篇关于Firestore 集合查询作为 Flutter 中的流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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