flutter - 在颤振中实现搜索建议
问题描述
我的愿望是实现一个按标签搜索的功能,当用户继续输入搜索词时,它会返回建议。
我的模型具有以下结构
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;
}
}
我也希望搜索与建议一起使用。我怎样才能做到这一点?
解决方案
如果您想更好地控制字符串匹配,我建议您查看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
函数将返回包含搜索字符串的任何标签。
推荐阅读
- wpf - 项目控件中的 WPF 嵌套模板绑定
- python - 使用 keras 生成新模型
- html - 即使给定相同的属性和值,按钮的大小也不同
- mongodb - 无法启动 MongoDB - IndexCatalog 留下了索引
- c# - UWP VS2017 - Xaml 内部错误错误 WMC9999:此成员“值”有多个项目,请使用 Items 属性
- php - Laravel proc_open(): 分叉失败
- android - Circular background for toolbar icons
- odoo - 如何获取客户发票行数?
- python - 具有多个 tbodies 的 Python Dash DataTable
- bash - How to format many uses of the && operator with multi line script?