Flutter Firebase - Search for documents which contain a string for

Viewed 4319

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?

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

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.

Related