Home > Software engineering >  How to sort list of file in order of latest to oldest
How to sort list of file in order of latest to oldest

Time:12-05

Currently, I am fetching a list of video files present in the directory using the following code

var videoList = _videoDir
          .listSync()
          .map((item) => item.path)
          .where((item) => item.endsWith(".mp4"))
          .toList(growable: true);

This generates a video list in random order. How can I fetch files in order of latest to oldest?

Update

I already tried to use the startsync() function at the end of the code but it cant be used on the type String when used after .toList()

CodePudding user response:

Use stat() or statSync() function of File class to sort the list in desired order.

  var videoList = videoDir.listSync()
    .where((e) => e.path.endsWith('.mp4'))
    .toList()
    ..sort((l, r) => l.statSync().modified.compareTo(r.statSync().modified));

  var videosPathList = videoList.map((e) => e.path).toList();

Note

  • List is growable by default.
List<FileSystemEntity> toList({bool growable = true})
dart:core

Creates a [List] containing the elements of this [Iterable].

The elements are in iteration order. The list is fixed-length if [growable] is false.

APIs:

  • Related