0

I am using Flutter and I have a list of objects that I get from json api link, for example the json api looks like this:

"data":[
      {
         "id":1,
         "date":"07\/09\/2022",
         "time":"18:30",
         "name":"michael",
         "email":"michael@hotmail.com"
      },
      {
         "id":2,
         "date":"09\/09\/2022",
         "time":"13:10",
         "name":"John",
         "email":"123@hotmail.com"
      }
 ]

I want to sort it not just by date but also by time.

I was able to sort it by date but it is not working with date and time at the same time.

Here is the code:

data.sort((a, b) => b.date.compareTo(a.date));

(data is the name of the list)

How can I change this so that it sorts by date and time ?

Thanks.

Mike
  • 137
  • 1
  • 2
  • 10
  • From the api response, you construct your list of models that will contain a DateTime object an sort the list by this property of the model. – Alex Terente Sep 15 '22 at 18:09
  • is this helpful? https://stackoverflow.com/questions/61343000/dart-sort-list-by-two-properties – obywan Sep 15 '22 at 18:11
  • data.sort((a, b) { final bFullDate = b.date + b.time; final aFullDate = a.date + a.time; return bFullDate.compareTo(aFullDate); }); Have you tried something like this? – M14 Sep 15 '22 at 19:11
  • @M14 Thank you!!! It worked. Turn your comment to an answer so that I can accept it if you want. :) – Mike Sep 15 '22 at 19:33
  • 1
    Are you really sure that the accepted solution is right? Add another object with date 07/12/2022 and try again. It doesn't work for me... – TripleNine Sep 15 '22 at 19:58
  • @TripleNine Oh, you're right. What a shame. I updated the answer – M14 Sep 15 '22 at 20:51
  • @Mike Please update your code in case you didn't see the updated version. – TripleNine Sep 15 '22 at 21:14
  • is 07/09 july 9th or september 7th? That'll affect how it sorts. :) – Randal Schwartz Sep 15 '22 at 21:33

1 Answers1

1
 data.sort((a, b) {
    final bFullDate = b.date + b.time;
    final aFullDate = a.date + a.time;
    return bFullDate.compareTo(aFullDate);
  }); 

Edit

import 'package:intl/intl.dart';

DateFormat format = DateFormat('dd-MM-yyyy HH:mm');

data.sort((a, b) {
  final bFullDate = format.parse(b.date + ' ' + b.time);
  final aFullDate = format.parse(a.date + ' ' + a.time);
  return bFullDate.compareTo(aFullDate);
}); 
M14
  • 192
  • 1
  • 2
  • 10