Tim B.
Tim B.

Reputation: 88

Flutter Firebase - Search for documents which contain a string for

I have a question regarding a request to retrieve data from Google Cloud Firestore with specific parameters in my Flutter project.

I use the following code to check if a string in Firebase equals to a search query performed by a user:

var snapshot = await firestoreInstance.collection('categories/subcategory/items')
.where("parameter", isEqualTo: searchQuery).get()

This works if the user types exactly the name of the parameter stored in Firestore. But what I want is that it also works if only part of the searchQuery string is stored in the Firestore parameter.

I found a solution on https://medium.com/flutterdevs/implement-searching-with-firebase-firestore-flutter-de7ebd53c8c9 for this. In the article an array is created with all possibile searches for the parameter. But I think that is a bit complex and you have to generate a lot of new data in Firestore just to search for the article.

Is there a way to do this in an easier way so that you can use an operator as "contains" instead of "isEqualTo" in Flutter with Firebase for the request?

Upvotes: 4

Views: 6824

Answers (2)

krazy
krazy

Reputation: 347

var snapshot = await firestoreInstance
  .collection('categories/subcategory/items')
  .where(
    'parameter',
    isGreaterThanOrEqualTo: searchQuery,
    isLessThan: searchQuery + 'z'
  )
  .get();

Upvotes: 4

Nicolas Ebeling
Nicolas Ebeling

Reputation: 177

Try this:

var snapshot = await firestoreInstance
      .collection('categories/subcategory/items')
      .where(
        'parameter',
        isGreaterThanOrEqualTo: searchQuery,
        isLessThan: searchQuery.substring(0, searchQuery.length - 1) +
            String.fromCharCode(searchQuery.codeUnitAt(searchQuery.length - 1) + 1),
      )
      .get();

I based the variable names on your example.

Upvotes: 1

Related Questions