【问题标题】:Firestore: Flutter pugin, error when trying to sort the data by a fieldFirestore:Flutter pugin,尝试按字段对数据进行排序时出错
【发布时间】:2020-08-03 15:34:27
【问题描述】:

我正在尝试按整数字段对存储在 Firestore 中的文档进行排序,但是在尝试这样做时,我收到了这个错误。 type Query is not a subtype of type Collection Reference

我的代码是

final CollectionReference timetableCollection = Firestore.instance.collection('timetables').orderBy('Period'); 

其中句点仅包含整数。如果我不执行 orderBy 部分,则代码可以正常工作。 我查看了文档,它说 CollectionReference 在 Query 上扩展,所以我不明白在哪里修复。

【问题讨论】:

  • 这看起来不像完整的代码。请编辑问题以显示任何人都可以用来重现问题的代码,并确保充分解释错误消息所指的内容。
  • 抱歉,我的格式搞砸了,只显示了最后一部分代码。

标签: firebase flutter dart google-cloud-firestore


【解决方案1】:

我相信您可以从 API 文档中看到,collection() 返回一个 CollectionReference,orderBy() 返回一个查询。

确实,CollectionReference 是 Query 的子类。但是,这并不意味着所有 Query 对象也是 CollectionReference 对象。这意味着所有的 CollectionReference 对象也是 Query 对象

如果要使用通用数据类型,请使用 Query。这些代码行都应该编译:

final Query timetableQuery = Firestore.instance.collection('timetables'); 
final Query timetableOrderedQuery = Firestore.instance.collection('timetables').orderBy('Period'); 

【讨论】:

  • 谢谢,这修复了错误。然而,事实证明需要 CollectionReference 数据类型,因为我在另一个函数中使用了timetableCollection.document().setData(...)。所以,我最终声明了这两种数据类型。感谢您为我指明正确的方向。
猜你喜欢
  • 1970-01-01
  • 2021-03-28
  • 1970-01-01
  • 2017-05-03
  • 1970-01-01
  • 2018-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多