这是我希望从Firestore获取PostTag
对象列表的函数。
class UsersDatabaseService {
final String uid;
UsersDatabaseService({this.uid});
final CollectionReference settingsCollection = Firestore.instance.collection('accountSettings');
static CollectionReference postTagListCollection= Firestore.instance.collection('postTagList');
...some code here...
static Future<List<PostTag>> getPostTags(String query)async{
try {
return await postTagListCollection.where((tag) => tag.name.toLowerCase().contains(query.toLowerCase())).getDocuments()
.then((snapshot) => yieldPostTags(snapshot));
}catch(e){
print(e.toString());
return null;
}
}
static List<PostTag> yieldPostTags(QuerySnapshot snapshot) {
try {
return snapshot.documents.map((doc) {
print(doc.data['name']);
return PostTag(
category: doc.data['category'] ?? '',
position: doc.data['position'] ?? 0,
name: doc.data['name'] ?? ''
);
}).toList();
}catch(e){
print(e.toString());
return null;
}
}
我尝试了另一篇类似的文章中建议的解决方案,即将postTagListCollection
的类型更改为Query
而不是CollectionReference
。伴随着这个错误I/flutter (31837): 'package:cloud_firestore_platform_interface/src/method_channel/method_channel_query.dart': Failed assertion: line 119 pos 12: 'field is String || field is FieldPath': Supported [field] types are [String] and [FieldPath].
我如何解决这个错误 最佳答案
CollectionReference
类是Query
类的子类,由于collection()
方法返回CollectionReference
,因此您可以执行以下操作:
static CollectionReference postTagListCollection= Firestore.instance.collection('postTagList');
问题在这里: return await postTagListCollection.where((tag) => tag.name.toLowerCase().contains(query.toLowerCase())).getDocuments()
where()
方法用于查询数据库,例如:return await postTagListCollection.where("name", isEqualTo: "john").getDocuments()
您可以执行以下查询: Query where(
dynamic field, {
dynamic isEqualTo,
dynamic isLessThan,
dynamic isLessThanOrEqualTo,
dynamic isGreaterThan,
dynamic isGreaterThanOrEqualTo,
dynamic arrayContains,
List<dynamic> arrayContainsAny,
List<dynamic> whereIn,
bool isNull,
}) {