我有一个产品列表
List<Product>
项目值来自字符串变量,并且有一个搜索,我们可以从中选择多个参数,如颜色、形状、尺寸等。所以我想过滤各种参数的列表。
DiamondSearchParameters
正在表单中使用,许多参数是多选的,我想根据所选参数过滤列表。考虑列表 List<Product>
包含带有字符串值的 api 数据,并且在 DiamondSearchParameters
中所有都是颜色、形状等的静态数据。
class DiamondSearchParameters extends Equatable {
late final Set<Shape>? shapes;
late final SplayTreeSet<CaratRangeItem>? caratRangeItems;
late final DiamondColor? color;
late final Set<SearchDiamondFormOption>? colorVariants;
late final Set<SearchDiamondFormOption>? fancyIntensity;
late final Set<SearchDiamondFormOption>? fancyOvertone;
late final Set<SearchDiamondFormOption>? clarity;
late final DiamondMake? diamondMake;
}
尝试以这种方式对数据进行排序,想要更好的方法
_getSearchCount(
DiamondSearchParameters param,
) {
final List<Product> sortedDiamondsList = product!;
final List<Product> temp = [];
sortedDiamondsList.forEach((element) {
param.shapes?.forEach((shapes) {
if(element.shapeName == shapes.toString()){
debugPrint('shape---${element.shapeName}');
temp.add(element);
}
});
if(param.color == element.color){
debugPrint('color---${element.color}');
}
param.colorVariants?.forEach((colorVariants) {
debugPrint('colorVariants---${element.color}');
});
});
您可以使用 OR 运算符设置循环
_getSearchCount(
DiamondSearchParameters param,
) {
final List<Product> sortedDiamondsList = product!;
final List<Product> temp = [];
sortedDiamondsList.forEach((element) {
if (param.shapes?.any((shape) => shape.toString() == element.shapeName) ||
param.color == element.color ||
param.colorVariants?.any((color) => color == element.color)) {
temp.add(element);
}
});
return temp;
}