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

Flutter对接ASP.NET API:按ID筛选最新dateofinsp数据

解决按Drainage ID筛选最新检查记录的问题

核心处理逻辑

要实现需求,只需三步:

  • 按drainage id对所有返回记录分组
  • 每组内按dateofinsp字段降序排序(最新记录排最前)
  • 从每组中取出第一条记录

代码实现

1. 确认数据模型类

根据API返回的JSON结构,你的模型类可参考如下(按需调整字段):

class InspectionRecord {
  final int drainageId;
  final DateTime dateOfInsp;
  // 其他业务字段,比如检查结果、备注等

  InspectionRecord({
    required this.drainageId,
    required this.dateOfInsp,
    // 其他字段的构造参数
  });

  // JSON转模型的工厂方法
  factory InspectionRecord.fromJson(Map<String, dynamic> json) {
    return InspectionRecord(
      drainageId: json['drainageId'] as int,
      dateOfInsp: DateTime.parse(json['dateofinsp'] as String),
      // 其他字段解析逻辑
    );
  }
}

2. 修改ApiProvider的处理代码

替换你原有错误的排序逻辑,改用以下代码处理API返回数据:

Future<List<InspectionRecord>> getLatestInspections() async {
  final response = await http.get(Uri.parse('你的API接口地址'));
  
  if (response.statusCode == 200) {
    List<dynamic> rawData = json.decode(response.body);
    List<InspectionRecord> allRecords = rawData.map((item) => InspectionRecord.fromJson(item)).toList();

    // 第一步:按drainageId分组
    Map<int, List<InspectionRecord>> groupedRecords = {};
    for (var record in allRecords) {
      groupedRecords.putIfAbsent(record.drainageId, () => []).add(record);
    }

    // 第二步:每组取最新记录
    List<InspectionRecord> latestRecords = [];
    groupedRecords.forEach((_, records) {
      // 方式1:排序后取第一条
      records.sort((a, b) => b.dateOfInsp.compareTo(a.dateOfInsp));
      latestRecords.add(records.first);

      // 方式2:直接遍历找最大值(性能更优,数据量大时推荐)
      // InspectionRecord latest = records.reduce((a, b) => a.dateOfInsp.isAfter(b.dateOfInsp) ? a : b);
      // latestRecords.add(latest);
    });

    return latestRecords;
  } else {
    throw Exception('加载检查记录失败');
  }
}

3. 关键注意事项

  • 确保dateofinsp字段是标准ISO格式字符串,若API返回非标准格式,需用DateFormat类做适配解析
  • 如果API返回的drainage id是字符串类型,将分组Map的键类型改为String即可
  • 若API支持,优先考虑在后端直接返回分组后的最新记录,减少前端数据处理压力

验证示例

假设API返回JSON如下:

[
  {"drainageId": 1, "dateofinsp": "2024-01-01T10:00:00"},
  {"drainageId": 1, "dateofinsp": "2024-03-15T14:30:00"},
  {"drainageId": 2, "dateofinsp": "2024-02-20T09:15:00"},
  {"drainageId": 2, "dateofinsp": "2024-04-05T16:45:00"}
]

处理后会得到两条记录:

  • drainageId=1,dateofinsp=2024-03-15
  • drainageId=2,dateofinsp=2024-04-05

内容的提问来源于stack exchange,提问作者user21497668

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 03:35:16