首页 > 解决方案 > 在颤振中实现搜索建议

问题描述

我的愿望是实现一个按标签搜索的功能,当用户继续输入搜索词时,它会返回建议。

我的模型具有以下结构

class BuyerPost{
  final String postId;
  final String buyer;
  final String description;
  final GeoPoint locationCoordinates;
  final List tags;// search by this
  final List imageUrls;
  final String category;
  final Timestamp postTime;
  final Timestamp expireTime;
  final int responsesCount;
  final String status;

  BuyerPost({
    this.postId,
    this.buyer,
    this.description,
    this.locationCoordinates,
    this.tags,
    this.imageUrls,
    this.category,
    this.postTime,
    this.expireTime,
    this.responsesCount,
    this.status,
  });

}

如上面的代码片段,模型的 tags 属性是用户设置的标签列表。

到目前为止,我仅在搜索词与标签列表中的标签名称完全匹配时才实现搜索以返回文档。

示例: 如果用户在帖子具有类似标签的情况下搜索“bl”,则在tags:['black','white']他/她完成它以喜欢“黑色”之前不会返回任何内容。

这是搜索的片段

  //single buyer post
  Stream <List<BuyerPost>> get searchBuyerPost {
    try {
      return buyerPostCollection.snapshots()
          .map(yieldSearchedBuyerPosts);
    }catch(e){
      print(e.toString());
      return null;
    }
  }

   List<BuyerPost> yieldSearchedBuyerPosts(QuerySnapshot snapshot) {
    try {
      return snapshot.documents.map((doc) {
        print(doc.data['name']);
        return BuyerPost(
          postId: doc.data['postId'] ?? '',
          description: doc.data['description'] ?? '',
          locationCoordinates: doc.data['locationCoordinates'] ?? '',
          imageUrls: doc.data['imageUrl'] ?? [],
          tags: doc.data['tags'] ?? [],
          category: doc.data['category'] ?? '',
          postTime: doc.data['postTime']?? Timestamp(0,0),
          expireTime: doc.data['expireTime']?? Timestamp(0,0),
          responsesCount: doc.data['responsesCount']?? 0,
          status: doc.data['status'] ?? '',
        );
      }).where((post) =>
          post.tags.contains(searchTerm.toLowerCase()
      )
      ).toList();
    }catch(e){
      print(e.toString());
      return null;
    }
  }

我也希望搜索与建议一起使用。我怎样才能做到这一点?

标签: fluttersearchtags

解决方案


如果您想更好地控制字符串匹配,我建议您查看Regex

这是一个例子:

List<BuyerPost> match(String searchString, List<BuyerPost> posts) {
  RegExp searchedStringRegex = RegExp(searchString);
  return posts.where((post) => post.tags.any((tag) => searchedStringRegex.hasMatch(tag)));
}

在这里,该match函数将返回包含搜索字符串的任何标签。


推荐阅读