【问题标题】:Using where() on a collection in Streambuilder keeps returning null在 Streambuilder 中的集合上使用 where() 不断返回 null
【发布时间】:2021-03-03 12:36:02
【问题描述】:

我正在尝试在集合中查找符合特定条件的所有文档,并将其保存在 Streambuilder 中,以便我可以使用它返回的所有文档中的数据创建一个表。但是我在 Streambuilder 中的流一直为我在 Flutter 中的查询返回 null。我在 Python 中尝试了相同的查询,它返回了正确的文档。在流构建器中不可能有 where 查询吗?作为参考,这是一个网络应用程序。

这是我的代码

class ContainerCustomerTable extends StatefulWidget {
  final company;

  ContainerCustomerTable({this.company});
  @override
  _ContainerCustomerTableState createState() => _ContainerCustomerTableState();
}

class _ContainerTableState extends State<ContainerCustomerTable> {
  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
        stream: FirebaseFirestore.instance.collection(widget.company).where('some_criteria', isEqualTo: true).snapshots(),
        builder: (context, snapshot) {
          print(snapshot);
          QuerySnapshot docSnapshot = snapshot.data;
          if (docSnapshot != null) {
            return  Text('test1');
          } else{
            return LoadingIndicator();
          }

        }

    );

我打印快照只是为了检查它返回的内容,它给了我这个

AsyncSnapshot<QuerySnapshot>(ConnectionState.active, null, [cloud_firestore/unknown] NoSuchMethodError: invalid member on null: 'includeMetadataChanges')

所以它为该查询返回 null,但在 python 中的相同查询再次产生正确的结果。我做错了什么?

为了记录,当我运行以下命令时,它可以工作:

FirebaseFirestore.instance.collection(widget.company).doc('some_doc').snapshots()

但由于某种原因,当我只是在集合或位置上运行快照时,我收到上面发布的错误

【问题讨论】:

    标签: flutter google-cloud-firestore flutter-web


    【解决方案1】:

    我想通了。我的语法很好,是 firestore js 包错误。如果您将 Firestore 用于 Web 应用程序,请在您的 web/index.html 中使用此版本:

    <script src="https://www.gstatic.com/firebasejs/7.20.0/firebase-firestore.js"></script>
    

    不是最后一个版本 8.0.2,当我降级时一切都按预期工作。

    【讨论】:

      【解决方案2】:

      请注意,您还要在此处有数据之前打印快照并分配 docSnapshot:

      print(snapshot);
      QuerySnapshot docSnapshot = snapshot.data;
      if (docSnapshot != null) {
         return  Text('test1');
      } else{
         return LoadingIndicator();
      }
      

      为了安全,我想:

      if (snapshot.hasData) {
         print(snapshot);
         QuerySnapshot docSnapshot = snapshot.data;
         return  Text('test1');
      } else{
         return LoadingIndicator();
      }
      

      【讨论】:

      • 感谢您的建议。我只是在那里打印它以尝试调试问题所在。最终我的代码没有错,我只需要更改 firestore.js 的版本
      猜你喜欢
      • 2020-12-19
      • 2021-10-07
      • 2020-07-12
      • 2021-04-19
      • 2019-10-01
      • 1970-01-01
      • 2021-01-28
      • 2016-04-06
      • 1970-01-01
      相关资源
      最近更新 更多