I've got a list of object which after looping I'm trying to sort the final list by given ISO8601 format favouriteDateTime: 2022-12-16T10:46:55.551Z. There are mutiple sorting method but which one to use and how to sort it.
List<Movies> get Movies{
List<Movies> favMoviesList = <Movies>[];
for (final category in _appData.categories) {
for (final series in category.series!) {
final favMovies = series.movie!
.where((movie) =>
movie.stats != null && movie.stats!.isFavourite == true)
.toList();
if (favMovies.length > 0) {
List<Movies> sorted = favMovies
..sort((a, b) => b.stats!.favoriteDateTime!
.compareTo(a.stats!.favoriteDateTime!));
favMoviesList.addAll(sorted);
}}}
return favMoviesList;
}
CodePudding user response:
Looks like you've already got a working implementation here. ISO8601 timestamps can just be sorted with string comparison - for two ISO strings a
and b
, a > b
will always be true if time a
is after time b
, and the inverse is also true.
As far as the actual sorting method goes, you've got the right idea here with using sort()
. Just make sure you only have one period -- favMovies.sort()
, not favMovies..sort()
.
Also, List.sort()
does not return the sorted list, it sorts the list in place. So your sorting code should be:
favMovies.sort((a, b) =>
b.stats!.favoriteDateTime!.compareTo(a.stats!.favoriteDateTime!)
);
favMoviesList.addAll(favMovies);