类型'List <dynamic>'不是'函数结果'的类型'CollectionReference'的子类型

时间:2020-09-03 13:51:00

标签: firebase flutter dart google-cloud-firestore

这是我希望从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].

如何解决此错误

1 个答案:

答案 0 :(得分:2)

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,
  }) {