flutter Sorting arraylist by Date

2,266

You'll need to parse your Strings to DateTimes. Since DateTime parse() method won't accept Strings in the format you provided, you can do something like this:

List<String> strings = ['04-07-2020', '17-06-2020', '16-06-2020', '19-06-2020', '18-06-2020', '22-06-2020'];
List<DateTime> dateTimes = [];
  
strings.forEach((string) {
  var splitted = string.split('-');
  var day = splitted[0];
  var month = splitted[1];
  var year = splitted[2];
  var formatted = '$year-$month-$day';
  dateTimes.add(DateTime.parse(formatted));
});
  
dateTimes.sort((a, b) => a.compareTo(b));

Just adapt it for your structure!

Share:
2,266
Sunil
Author by

Sunil

Updated on December 22, 2022

Comments

  • Sunil
    Sunil over 1 year

    In My streamBuilder I have Array list contains dates having format(dd-MM-yyyy). I want to arrange the list in ascending order. The code I used in StreamBuilder after getting Datasnapshot

     Map<dynamic, dynamic> data = snap.data.snapshot.value;
    
                  List item = [];
                  data.forEach(
                      (index, data) => item.add(
                          {"key": index, ...data}
                          )
                  );
                  item..sort((a,b)=>a['key'].compareTo(b['key']));
    

    I am expecting result as 16-06-2020 17-06-2020 18-06-2020 19-06-2020 22-06-2020 04-07-2020

    The result I am getting is 04-07-2020 16-06-2020 17-06-2020 18-06-2020 19-06-2020 22-06-2020

    • julemand101
      julemand101 almost 4 years
      What type is a['key']? It looks like it is a String which explain the weird sorting and not DateTime?
    • Sunil
      Sunil almost 4 years
      @julemand101 yes it is child value read from Firebase Database. Can you please help me how to sort it in DateTime?
    • Danaru
      Danaru almost 4 years
      You need to parse a['key'] and b['key'] to DateTime. api.flutter.dev/flutter/dart-core/DateTime/parse.html