Reputation: 161
The logic behind my search function is, The searchKey field stored a value's capitalized first letter. Basically, I will store any value with it's searchKey; which is the values First letter capitalized and stored in a new field called SearchKey.
I wanted to display searched results from an array in Cloud Firestore. The code I have written for a string field works perfectly. Here it is:
void initiateSearch(String val) async {
if (val.length == 0) {
setState(() {
queryResultSet = [];
tempSearchStore = [];
queryResultGigSet = [];
tempSearchGigStore = [];
queryResultTagSet = [];
tempSearchTagStore = [];
});
}
String capitalizedValue =
val.substring(0, 1).toUpperCase() + val.substring(1);
if (queryResultGigSet.length == 0 && val.length == 1) {
// SearchService().searchByName(val);
await databaseReference
.collection('posts')
.where('searchKey', isEqualTo: val.substring(0, 1).toUpperCase())
.getDocuments()
.then((QuerySnapshot docs) {
for (int i = 0; i < docs.documents.length; ++i) {
setState(() {
isLoading = false;
queryResultGigSet.add(docs.documents[i].data);
});
}
});
} else {
tempSearchGigStore = [];
queryResultGigSet.forEach((element) {
if (element['category'].startsWith(capitalizedValue)) {
setState(() {
isLoading = false;
tempSearchGigStore.add(element);
});
}
});
}
But For an array it isn't working. The code I have written is :
if (queryResultTagSet.length == 0 && val.length == 1) {
// SearchService().searchByName(val);
await databaseReference
.collection('posts')
.where('searchKeyTags', arrayContains: val.substring(0, 1).toUpperCase())
.getDocuments()
.then((QuerySnapshot docs) {
for (int i = 0; i < docs.documents.length; ++i) {
setState(() {
isLoading = false;
queryResultTagSet.add(docs.documents[i].data);
});
}
});
} else {
tempSearchTagStore = [];
queryResultTagSet.forEach((element) {
if (element['tags'].values.startsWith(capitalizedValue)) {
setState(() {
isLoading = false;
tempSearchTagStore.add(element);
});
}
});
}
}
}
Upvotes: 0
Views: 108
Reputation: 161
the answer is
if (queryResultTagSet.length == 0 && val.length == 1) {
// SearchService().searchByName(val);
await databaseReference
.collection('posts')
.where('searchKeyTags',
arrayContains: val.substring(0, 1).toUpperCase())
.getDocuments()
.then((QuerySnapshot docs) {
for (int i = 0; i < docs.documents.length; ++i) {
setState(() {
isLoading = false;
queryResultTagSet.add(docs.documents[i].data);
});
}
});
} else {
tempSearchTagStore = [];
queryResultTagSet.forEach((element) {
List.from(element['tags']).forEach((p) {
if (p.toString().startsWith(capitalizedValue)) {
setState(() {
isLoading = false;
tempSearchTagStore.add(element);
});
}
});
});
}
Upvotes: 1