如何修复Flutter中的mapIndexed函数并添加过滤条件?
解决方案
直接在转换前添加过滤逻辑,先剔除score为0的元素再进行转换即可,修改后的代码如下:
List<TimeSeriesValues> list = (data["list"] as List) .where((e) => int.parse(e['score']) != 0) .mapIndexed((index, e) => TimeSeriesValues( DateTime.tryParse(e["detectedAt"])!, int.parse(e['score']), )) .toList();
逻辑说明
where((e) => int.parse(e['score']) != 0):先过滤列表,只保留score解析为整数后不等于0的元素- 后续的
mapIndexed仅处理过滤后的有效元素,避免无效转换操作 - 最后通过
toList()生成最终的TimeSeriesValues列表
如果需要在转换逻辑内处理过滤(效率略低于先过滤再转换),也可以用这种写法:
List<TimeSeriesValues> list = (data["list"] as List) .mapIndexed((index, e) { final score = int.parse(e['score']); return score != 0 ? TimeSeriesValues(DateTime.tryParse(e["detectedAt"])!, score) : null; }) .whereType<TimeSeriesValues>() .toList();
这种方式会先遍历所有元素并尝试转换,再过滤掉返回null的项,适合需要在转换阶段额外处理其他逻辑的场景。
内容的提问来源于stack exchange,提问作者newbiras
相关产品推荐
相关产品推荐

