0

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, this is the solution. In my case, createdAt is get from firebase thanks to fromJson method, so I get the error "The method 'compareTo' was called on null". Do you have an idea how to fix this please ?
There are multiple ways that you could do, you could remove the null values with a where clause. Or you could improve the sort function of how you want to handle a null value. I update the codepen with one of the options.
I fixed the problem, createdAt was null on class B it working perfectly now. Thanks for your time and this where clause tip that I did not know

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.