I'm working in flutter app i want get list of file in local Directory sorted by creation time
my list :
Directory appDirectory = Directory('/storage/emulated/0/myapp');
var fileList = [];
fileList = appDirectory.listSync().map((item) => item.path).where((item) => item.endsWith('.pdf')).toList(growable: false);
but the items in list sorted random . How can i sort list by file creation time
CodePudding user response:
First, be aware that FileStat
does not expose creation times, which isn't surprising since many filesystems don't store creation time and store only modification time. If modification time is acceptable, you can call File.stat
for each File
, collect the results, and sort by that.
var fileList = appDirectory.listSync().map((item) => item.path).where((item) => item.endsWith('.pdf')).toList(growable: false);
// Compute [FileStat] results for each file. Use [Future.wait] to do it
// efficiently without needing to wait for each I/O operation sequentially.
var statResults = await Future.wait([
for (var path in fileList) FileStat.stat(path),
]);
// Map file paths to modification times.
var mtimes = <String, DateTime>{
for (var i = 0; i < fileList.length; i = 1)
fileList[i]: statResults[i].changed,
};
// Sort [fileList] by modification times, from oldest to newest.
fileList.sort((a, b) => mtimes[a]!.compareTo(mtimes[b]!));
CodePudding user response:
Sorting the fileList
by date-time attribute should do the trick
Example:
fileList.sort((a,b) {
return DateTime.parse(a["dateTimeAttribute"]).compareTo(DateTime.parse(b["dateTimeAttribute"]));
});