How to sort/order a list by date in dart/flutter?

convert to DateTime

import 'package:intl/intl.dart';

void main() {
  List products = [
    "2019-11-25 00:00:00.000",
    "2019-11-22 00:00:00.000",
    "2019-11-22 00:00:00.000",
    "2019-11-24 00:00:00.000",
    "2019-11-23 00:00:00.000"
  ];
  List<DateTime> newProducts = [];
  DateFormat format = DateFormat("yyyy-MM-dd");

  for (int i = 0; i < 5; i++) {
    newProducts.add(format.parse(products[i]));
  }
  newProducts.sort((a,b) => a.compareTo(b));

  for (int i = 0; i < 5; i++) {
    print(newProducts[i]);
  }
}

without convert to DateTime

import 'package:intl/intl.dart';

void main() {
  List products = [
    "2019-11-25 00:00:00.000",
    "2019-11-22 00:00:00.000",
    "2019-11-22 00:00:00.000",
    "2019-11-24 00:00:00.000",
    "2019-11-23 00:00:00.000"
  ];

  products.sort((a,b) => a.compareTo(b));

  for (int i = 0; i < 5; i++) {
    print(products[i]);
  }
}

In your example above, expiry is a String, not a DateTime object. You have a few options here, depending on what you want to achieve.

The easiest solution would be to use String's built in compareTo method, which allows sorting Strings. Those timestamps are already in a sortable format, so this would work:

products.sort((a,b) {
    return a.compareTo(b);
 });

Or more concise:

products.sort((a,b) => a.compareTo(b));

This is pretty basic. Like pskink mentioned in the comment, building on this you could convert the Strings to actual DateTime objects.

DateTime expiryAsDateTime = DateTime.parse(expiry);

DateTime also has a built in compareTo method, so the code snippet above would work with DateTimes as well as Strings.

If you want to reverse the order, just swap a and b.


I fixed it by changing changing a.expiry into a['expiry'] and b.expiry into b['expiry']

products.sort((a,b) {
 var adate = a['expiry'] //before -> var adate = a.expiry;
 var bdate = b['expiry'] //before -> var bdate = b.expiry;
 return adate.compareTo(bdate); //to get the order other way just switch `adate & bdate`
});

Tags:

Dart

Flutter