skip to Main Content

If I use the code, I can receive the data correctly.
However, using .where, I get the error:

The method ‘where’ isn’t defined for the type ‘DocumentReference’.
Try correcting the name to the name of an existing method, or defining a method named ‘where’.

code:

chamaBancoDeDados(curso, materia, id, dificuldade) {
    Map<String, dynamic> dados = {};
    final documentoRef = FirebaseFirestore.instance
        .collection('cursos')
        .doc(curso)
        .collection(materia)
        .doc(id)
        .where('dificuldade', arrayContainsAny: ['normal']);
    documentoRef
        .get()
        .then((DocumentSnapshot documento) {
      if (documento.exists) {
        try {
          dados = documento.data() as Map<String, dynamic>;
          print("dados são: $dados");
        } on StateError catch (e) {
          print('Erro tentando adquirir o documento no banco de dados: $e');
        }
      } else {
        print('O documento não existe no banco de dados');
      }
    });
    return dados;
  }
}

I’ve already searched a lot on the internet, including the Firebase documentation, but I don’t know where I’m going wrong.

3

Answers


  1. Chosen as BEST ANSWER

    I make this and works how I wanted:

        final teste = FirebaseFirestore.instance
        .collection('cursos')
        .doc(curso)
        .collection(materia)
        .where('dificuldade', arrayContainsAny: [dificuldade]); 
    await teste
        .get()
        .then((event) {
        print("${doc.id} => ${doc.data()}");
      }
    }, onError: (e) => print("Error completing: $e"));
    

  2. If you see in line 7 of your code, that gets a document from firestore, and you cant use .where() on a document.

    .where() is used for collections to check the condition for all documents (in that collection) and return the documents which satisfy the need.

    From the above given info, I’d suggest you to remove 7th line of code and try again.

    Please share your Firestore hierarchy so that we could suggest a better way to perform your queries.

    Login or Signup to reply.
  3. Your current code tries to read a single document with a known ID, in which case there is no way to further filter the data with a where clause. So if you only want to read that single document, remove the where:

    final documentoRef = FirebaseFirestore.instance
        .collection('cursos')
        .doc(curso)
        .collection(materia)
        .doc(id);
    

    If on the other hand, you want to read all documents from the cursos collection with a normal difficulty level, that be done by removing the .doc(id) clause:

    final documentoRef = FirebaseFirestore.instance
        .collection('cursos')
        .doc(curso)
        .collection(materia)
        .where('dificuldade', arrayContainsAny: ['normal']);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search