Comforti Chambeshi
Comforti Chambeshi

Reputation: 139

type 'Query' is not a subtype of type 'CollectionReference'

I am trying to sort my data by date_posted but i am getting 'type 'Query' is not a subtype of type 'CollectionReference'.' I have tried searching for the solutions but all in vain! My code:

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);
  }
}

When i change it to:

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

Am getting 'type 'Query' is not a subtype of type 'CollectionReference''

Upvotes: 1

Views: 578

Answers (2)

Doug Stevenson
Doug Stevenson

Reputation: 317913

CollectionReference is a subclass of Query. You can assign a CollectionReference to a Query, but not the other way around. You will have to restructure your code more like this:

  // 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);
  }

Upvotes: 2

Akif
Akif

Reputation: 7660

Change this

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

into this

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

Upvotes: 3

Related Questions