Flutter中ImagePicker选图后保存与重启加载失败(仅iOS)
iOS端重启后图片加载失败的原因与修复方案
问题代码
File? imageFile; ImagePicker imagePicker = ImagePicker(); Future<File?> getImage(ImageSource imageSource) async { final XFile? pickedFile = await imagePicker.pickImage(source: imageSource); if (pickedFile == null) { return null; } return File(pickedFile.path); } // source is camera // save to SharedPreferences final String duplicateFilePath = await getApplicationDocumentsDirectory().then((value) => value.path); final fileName = basename(file.path); final File newImage = await file.copy('$duplicateFilePath/$fileName'); // save newImage.path
问题表现
从相机选图后复制到应用文档目录,将完整路径存入SharedPreferences,iOS重启应用后加载图片报PathNotFoundException,提示文件不存在;Android端无此异常。
原因分析
iOS沙盒的应用容器ID(路径中类似7D7645C5-CAF6-43F5-A484-CA93872D2996的部分)每次重启应用都会随机变更,你保存的完整绝对路径包含了旧的容器ID,重启后路径自然失效。而Android的应用沙盒路径不会随重启改变,所以没有这个问题。
修复方案
不要保存完整绝对路径,只存文件名,加载时动态拼接当前有效的文档目录路径:
- 保存时仅存储文件名到SharedPreferences:
// 替换原保存路径的逻辑 final fileName = basename(newImage.path); final prefs = await SharedPreferences.getInstance(); await prefs.setString('saved_image_filename', fileName);
- 加载图片时重新生成有效路径:
// 加载图片的逻辑 final prefs = await SharedPreferences.getInstance(); final fileName = prefs.getString('saved_image_filename'); if (fileName != null) { final docDir = await getApplicationDocumentsDirectory(); final validImagePath = '${docDir.path}/$fileName'; // 使用validImagePath加载图片即可 }
这样每次启动都获取当前应用的文档目录,再和保存的文件名拼接,就能正确定位到图片文件。
内容的提问来源于stack exchange,提问作者Donghoon Kim
相关产品推荐
相关产品推荐

