颤振 |如何按创建时间对文件列表进行排序

Flutter | How to Sort file list by creation time

我在 flutter 应用程序中工作 我想获取本地目录中按创建时间排序的文件列表

我的清单:

Directory appDirectory = Directory('/storage/emulated/0/myapp');
var fileList = [];
fileList = appDirectory.listSync().map((item) => item.path).where((item) => item.endsWith('.pdf')).toList(growable: false);

但列表中的项目是随机排序的。 我如何按文件创建时间对列表进行排序

按 date-time 属性对 fileList 进行排序应该可以解决问题

示例:

fileList.sort((a,b) {
    return DateTime.parse(a["dateTimeAttribute"]).compareTo(DateTime.parse(b["dateTimeAttribute"]));
});

首先,请注意每个 FileFileStat 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,收集结果并按其排序。

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]!));