You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter如何获取路径下所有以media开头的图片并存入列表?

修改后的代码实现
List<File> _imageFileList = [];

Future<List<File>> loadAllMediaImages() async {
  try {
    final Directory directory = await getApplicationDocumentsDirectory();
    // 遍历目录下所有实体,筛选符合条件的图片文件
    final List<File> mediaFiles = await directory.list()
        .where((entity) => entity is File)
        .map((entity) => entity as File)
        // 筛选文件名以'media'开头且后缀为.jpg的文件
        .where((file) => file.path.split('/').last.startsWith('media') && file.path.endsWith('.jpg'))
        .toList();
    
    _imageFileList = mediaFiles;
    return _imageFileList;
  } catch (e) {
    print("读取文件失败: $e");
    return [];
  }
}
关键修改说明
  • 调整函数返回类型为Future<List<File>>,适配返回文件列表的需求
  • 使用directory.list()遍历应用文档目录下的所有文件/目录
  • 两层过滤逻辑:
    • 先筛选出文件类型的实体(排除子目录)
    • 再匹配文件名规则:以media开头、以.jpg结尾
  • 将筛选结果赋值给_imageFileList并返回,同时保留异常捕获逻辑

如果需要支持更多图片格式(比如.png),可以修改后缀判断条件:

.where((file) {
  final fileName = file.path.split('/').last;
  return fileName.startsWith('media') && 
         (fileName.endsWith('.jpg') || fileName.endsWith('.png'));
})

内容的提问来源于stack exchange,提问作者Mat Koffman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 13:15:33