You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 08:15:55