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

Flutter中按TimeOfDay对模型列表排序及优化实现方案

解决方案:按TimeOfDay拆分并排序Medication列表

一、为现有实现添加排序逻辑

你的拆分逻辑可以正常工作,要对拆分后的列表按TimeOfDay排序,只需在返回列表前添加排序处理。TimeOfDay可通过比较小时和分钟实现排序:

List<Medication> getMedications(List<Medication> medications) {
  final tempList = <Medication>[];
  for (final medication in medications) {
    for (final element in medication.toBeTakenAt) {
      tempList.add(medication.copyWith(toBeTakenAt: [element]));
    }
  }
  // 按TimeOfDay排序:先比较小时,小时相同则比较分钟
  tempList.sort((a, b) {
    final timeA = a.toBeTakenAt.first;
    final timeB = b.toBeTakenAt.first;
    if (timeA.hour != timeB.hour) {
      return timeA.hour.compareTo(timeB.hour);
    }
    return timeA.minute.compareTo(timeB.minute);
  });
  return tempList;
}

二、更简洁的实现方式

可以使用expand方法简化拆分逻辑,再链式调用sort,让代码更紧凑:

List<Medication> getMedications(List<Medication> medications) {
  return medications
      .expand((med) => med.toBeTakenAt.map((time) => med.copyWith(toBeTakenAt: [time])))
      .toList()
      ..sort((a, b) {
        final timeA = a.toBeTakenAt.first;
        final timeB = b.toBeTakenAt.first;
        if (timeA.hour != timeB.hour) return timeA.hour.compareTo(timeB.hour);
        return timeA.minute.compareTo(timeB.minute);
      });
}

expand会自动将每个Medication实例按其toBeTakenAt中的时间拆分为多个实例,转成列表后直接执行排序,省去了显式嵌套循环,代码更简洁易读。

补充说明

  • 拆分后的每个Medication实例toBeTakenAt仅含一个元素,直接取first进行比较即可。
  • 若需倒序排序,只需将compareTo的结果取反,例如return -timeA.hour.compareTo(timeB.hour);

内容的提问来源于stack exchange,提问作者mohamed abderraouf douadi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 00:04:57