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
相关产品推荐
相关产品推荐

