我的搜索功能背后的逻辑是,searchKey字段存储值的大写首字母。基本上,我将使用searchKey来存储任何值;这是首字母大写并存储在名为SearchKey的新字段中的值。
我想显示Cloud Firestore中某个数组的搜索结果。我为字符串字段编写的代码可以正常工作。在这里:
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);
});
}
});
}
但是对于数组,它不起作用。我写的代码是:
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);
});
}
});
}
}
}
答案 0 :(得分:1)
答案是
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);
});
}
});
});
}