Google Firestore: Query on substring of a property value (text search)

前端 未结 16 1337
抹茶落季
抹茶落季 2020-11-22 12:08

I am looking to add a simple search field, would like to use something like

collectionRef.where(\'name\', \'contains\', \'searchTerm\')

I tried

16条回答
  •  有刺的猬
    2020-11-22 12:50

    This worked for me perfectly but might cause performance issues.

    Do this when querying firestore:

       Future searchResults = collectionRef
            .where('property', isGreaterThanOrEqualTo: searchQuery.toUpperCase())
            .getDocuments();
    

    Do this in your FutureBuilder:

        return FutureBuilder(
              future: searchResults,
              builder: (context, snapshot) {           
                List searchResults = [];
                snapshot.data.documents.forEach((doc) {
                  Model model = Model.fromDocumet(doc);
                  if (searchQuery.isNotEmpty &&
                      !model.property.toLowerCase().contains(searchQuery.toLowerCase())) {
                    return;
                  }
    
                  searchResults.add(model);
                })
       };
    

提交回复
热议问题