Home > Software design >  how to sort list by date - flutter/dart
how to sort list by date - flutter/dart

Time:09-20

I'm using storage access framework to get media files from specific directory. I'm making the use of saf.cache() method which returns the list of string (basically media path)

but I need to sort this list of string by creation time/date. How can I do that?

https://pub.dev/packages/saf

  Future<List<String>> fetchImages() async {

      Saf saf = Saf('specific_directory');
      List<String>? cacheList = await saf.cache();
      List<String> imageList = cacheList!.where((element) => element.endsWith('.jpg')).toList(); // it returns In random order
      return imageList;
  }

CodePudding user response:

Use .sort property to do this.

try:

myList.sort((sl1, sl2) {
      String list1 = sl1['column1'] ?? '0';
      String list2 = sl2['column2'] ?? '0';
      return sl1.compareTo(sl2);
    });

CodePudding user response:

you can use a higher order method called sort

and user compareTo to compare between dates ex:

   var items = [
    'Default',
    'Difficulty',
    'Time',
    'Di',
  ];
items.sort((a,b)=>a.length.compareTo(b.length));
print(items);
//[Di, Time, Default, Difficulty]
  • Related