Home > Mobile >  RangeError (RangeError (index): Invalid value: Valid value range is empty: 0) with Cloud Firestore
RangeError (RangeError (index): Invalid value: Valid value range is empty: 0) with Cloud Firestore

Time:07-24

I know this question has been asked alot but this is very different, I am querying my firestore database to return users that a person searches. Then it returns the data of the specific person you are searching for. here is the code

      await firestore
      .collection('users')
      .where("email", isEqualTo: _search.text)
      .get()
      .then((value) {
    setState(() {
      userMap = value.docs[0].data();
      isLoading = false;
    });
  });

The problem is whenever I input a value in the search bar that is NOT a user on the database, it gives me that error "RangeError (RangeError (index): Invalid value: Valid value range is empty: 0)". I understand it's because the thing being searched for doesn't exist yet but I have no idea how to fix it, please help!

CodePudding user response:

You need to add a check with if statement that the length of value.docs is not equal to zero.

      .then((value) {
   if(value.docs.length.isNotEmpty){
 setState(() {
      userMap = value.docs[0].data();
      isLoading = false;
    });
}
   

CodePudding user response:

Write an if statement in the .then fallback function to see if value.docs.length is greater then 0 and if yes, use the code you have, and if not (in the else) it doesn't exist and write what it should do in that situation.

  • Related