Home > Net >  How do I get the latest/most recent item in the list with DateTime with a specific key?
How do I get the latest/most recent item in the list with DateTime with a specific key?

Time:12-09

I'm returning a flat List from my server with objects that contain a createdAt. I want to iterate through this list and find the most recent one created, sorted by a specific key, kind

for example, this is the data I'm receiving:

final list = [
  {id: '1a' kind: 'MOOD' createdAt: 2021-12-08 19:22:11.000Z},
  {id: '1b' kind: 'MOOD' createdAt: 2021-12-08 19:15:11.000Z},
  {id: '1c' kind: 'PRESSURE' createdAt: 2021-12-08 18:22:11.000Z},
  {id: '1d' kind: 'MOOD' createdAt: 2021-12-07 18:22:11.000Z},
  {id: '1e' kind: 'WEIGHT' createdAt: 2021-12-07 17:21:11.000Z},
]

I want to be able to get the most recent createdAt, by the item's kind, so, for example, I want to get MOOD's most recent entry, it would be

{id: '1a' kind: 'MOOD' createdAt: 2021-12-08 19:22:11.000Z}

Similarly, I want to get WEIGHT's most recent entry, which would return

  {id: '1e' kind: 'WEIGHT' createdAt: 2021-12-07 17:21:11.000Z},

I've tried using firstWhere, but I'm unsure how to find the most recent date of the list, so I'm a bit lost there. I also have access to collection if a method there is applicable.

CodePudding user response:

Your objects match the next type:

class Obj {
  final String id;
  final String kind;
  final String createdAt;
  
  Obj(this.id, this.kind, this.createdAt);
  
  String toString() {
    return 'Obj{id: $id, kind: $kind, createdAt: $createdAt}';
  }
}

So you can use the next method to get the most recent one:

Obj findEarliestByKind(List<Obj> list, String kind) {
  final elems = list.where((Obj item) => item.kind == kind).toList();
  elems.sort((a, b) => DateTime.parse(b.createdAt).compareTo(DateTime.parse(a.createdAt)));
  return elems[0];
}

Some additional notes:

  1. It's better to pass type as an Enum
  2. It's needed to handle parsing and empty list exceptions

CodePudding user response:

Try to use DateTime.parse to convert string to DateTime object. Then you can get milliseconds from epoch. For example:

  Map<String, dynamic> getElement(List list, String kind) {
  list.where((element) => element['kind'] == kind).toList().sort((a, b) {
    return DateTime.parse(b['createdAt']!).millisecondsSinceEpoch -
        DateTime.parse(a['createdAt']!).millisecondsSinceEpoch;
  });

  return list.first;
}
  • Related