Hęŋý Xǿxờ
Hęŋý Xǿxờ

Reputation: 43

Firestore is ignoring the where clause in the query in flutter

How can I find the document that matches the logged-in email?

When I tried with the below code but Firestore ignores the where clause and just brings all the documents in student collection whether it matches or not. I have read that manually adding index in the Firebase console works but I tried that(screenshot of the console) and no luck. Is there something wrong in the code or I didn't index it correctly?

update: the output of the code: the first print is the email but after that there should only be one print which is 'peV2zNJukJTWKxanR9Cx'- output image and also the structure of the data in firestore image: firebase console image

also if i replace the 'email' variable with '[email protected]' in the where clause, it works.

 @override
  void initState() {
    super.initState();
    getUserEmail();
    getData();
  }


    getUserEmail() async {
    try {
      final user = await _auth.currentUser();
      if (user != null) {
        loggedInUser = user;
        email = loggedInUser.email;
        print(email);
      }
    } catch (e) {
      print(e);
    }
  }

  getData() async {
    var documents = await _firestore
        .collection('students')
        .where('email', isEqualTo: email)
        .getDocuments();

    for (var document in documents.documents) {
      print(document.data['grade']);
    }
  }

and my pubspec.yaml:

    name: school
    description: A new Flutter application.
    
    
    version: 1.0.0+1
    
    environment:
      sdk: ">=2.1.0 <3.0.0"
    
    dependencies:
      flutter:
        sdk: flutter
    
    
      cupertino_icons: ^0.1.2
      firebase_core: ^0.4.5
      firebase_auth: ^0.16.1
      cloud_firestore: ^0.13.7
    
    
    dev_dependencies:
      flutter_test:
        sdk: flutter
     
    flutter:
      uses-material-design: true
      assets:
        - images/

Upvotes: 1

Views: 672

Answers (2)

Hęŋ&#253; Xǿxờ
Hęŋ&#253; Xǿxờ

Reputation: 43

i finally found the answer, since i am calling the two methods in the initState() and this function doesn't take async and await keywords the getData() function starts executing before the getUserEmail() finishes saving the email on the email variable. so the where clause gets a future rather than a value. therefore i merged the two functions into one function so they can await properly for the other to finish. and call that function in the initState()

Upvotes: 3

sameer kashyap
sameer kashyap

Reputation: 1166

Firestore ignores the where clause only when the parameter passed to compare is null or empty.

Are you sure getUserEmail() is being called before getData() and the email variable is actually being assigned the value?

Please try correcting these, and your problem should be solved.

Also, you do not require an index unless you are comparing two or more fields in the where clause.

Upvotes: 0

Related Questions