如何从扑扑的Cloud Firestore中的数组字段中搜索和显示结果?

问题描述 投票:0回答:1

我的搜索功能背后的逻辑是,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);
      });
    }
  });
}
}
 }
flutter google-cloud-firestore flutter-layout flutter-dependencies
1个回答
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);
        });
      }
    });
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.