简体   繁体   中英

Sort a list of different objects with the same property (timestamp) in Flutter/Dart

I want to sort by date a List which contains 2 different objects (ClassA and ClassB), with the same property timestamp "createdAt". I have tried this solution:

_list.sort((a, b) => a.createdAt.compareTo(b.createdAt));

It only works when _list contains a single type of objects (ClassA or ClassB) but not with both.

Anyone has an idea? Thank you.

Solution: create an abstract class with createdAt property and implement it on childs

I think the problem is that you have a list with dynamic type. Therefore I would recommend creating an abstract class that contains both information from ClassA and ClassB, so that the dart compiler understands.

List<Parent> _list = [
  ClassA(DateTime(2020, 04, 04)),
  ClassB(DateTime(2020, 03, 04)),
  ClassA(DateTime(2020, 02, 04)),
  ClassB(DateTime(2020, 01, 04))
];

_list.sort((a,b)=> b.createdAt.compareTo(a.createdAt));

abstract class Parent {
  DateTime createdAt;
}

class ClassA implements Parent {
  DateTime createdAt;
  ClassA(this.createdAt);
}

class ClassB implements Parent {
  DateTime createdAt;
  ClassB(this.createdAt);
}

Here is also a CodePen where I could sort the list.

https://codepen.io/md-weber/pen/RwWaMgz

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM