“ Query”类型不是“ CollectionReference”类型的子类型

时间:2020-10-13 13:45:50

标签: firebase flutter google-cloud-firestore

我试图按date_posted对数据进行排序,但是我得到的是“查询类型”不是“ CollectionReference”类型的子类型。我曾尝试寻找解决方案,但徒劳! 我的代码:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:kopala_dictionary/models/words.dart';

class DatabaseService {
  //cloud databse colection

  final CollectionReference wordsCollection =
      Firestore.instance.collection('words').orderBy('date_posted');

  Future insertData(String word, String english_translation,
      String bemba_translation, String user_id, DateTime date_posted) async {
    return await wordsCollection.document().setData({
      'word': word,
      'english_translation': english_translation,
      'bemba_translation': bemba_translation,
      'user_id': user_id,
      'date_posted': date_posted
    });
  }

  //words list from snappshots

  List<Words> _wordsFromSnapShots(QuerySnapshot snapshot) {
    return snapshot.documents.map((doc) {
      return Words(
        word: doc.data['word'],
        englishTranslation: doc.data['english_translation'],
        bembaTranslation: doc.data['bemba_translation'],
      );
    }).toList();
  }

  //Stream snapshots

  Stream<List<Words>> get words {
    return wordsCollection.snapshots().map(_wordsFromSnapShots);
  }
}

当我将其更改为:

final CollectionReference wordsCollection = Firestore.instance.collection('words').orderBy('date_posted');

正在获取“查询类型”的不是“ CollectionReference”类型的子类型

2 个答案:

答案 0 :(得分:2)

更改此

 final CollectionReference wordsCollection =
  Firestore.instance.collection('words').orderBy('date_posted');

进入

    final Query wordsCollection =
  Firestore.instance.collection('words').orderBy('date_posted');

答案 1 :(得分:2)

CollectionReference是Query的子类。您可以将CollectionReference分配给查询,但不能相反。您将必须像下面这样重新组织代码:

  // This refers to just the collection "words", no implied ordering
  final CollectionReference wordsCollection = Firestore.instance.collection('words');

  Stream<List<Words>> get words {
    // This forces an ordering on the documents in the collection
    return wordsCollection.orderBy('date_posted').snapshots().map(_wordsFromSnapShots);
  }