在 flutter 中实现搜索建议

Implementing search suggestions in flutter

我的愿望是实现按标签搜索的功能,当用户继续输入搜索词时,return会给出建议。

我的模型结构如下

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,
  });

}

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

到目前为止,我只实现了对 return 文档的搜索,前提是搜索词与标签列表中的标签名称完全匹配。

示例: 如果用户在 post 有像 tags:['black','white'] 这样的标签的情况下搜索 'bl' 它不会 return 任何东西直到 he/she 完成它以喜欢 'black'.

这是搜索的片段

  //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;
    }
  }

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

如果您想更好地控制字符串匹配,我建议您查看 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 函数将 return 任何包含搜索字符串的标签。