更新依赖后删除Storage图片报[firebase_storage/object-not-found]异常
Firebase Storage 删除文件报
[firebase_storage/object-not-found] 问题排查 问题现象
更新全部Firebase相关依赖包后,执行Storage图片删除操作时始终抛出未处理异常:[firebase_storage/object-not-found] No object exists at the desired reference,已确认Storage中对应目录存在,操作返回404错误。
报错日志
I/System.out(11910): (HTTPLog)-Static: isSBSettingEnabled false E/StorageException(11910): StorageException has occurred. E/StorageException(11910): Object does not exist at location. E/StorageException(11910): Code: -13010 HttpResult: 404 E/StorageException(11910): { "error": { "code": 404, "message": "Not Found. Could not delete object", "status": "DELETE_OBJECT" }} E/StorageException(11910): java.io.IOException: { "error": { "code": 404, "message": "Not Found. Could not delete object", "status": "DELETE_OBJECT" }} E/flutter (11910): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: [firebase_storage/object-not-found] No object exists at the desired reference.
原有删除代码
deleteApartments( PersonalApartment personalApartment, Function apartmentDeleted) async { if (personalApartment.imageUrl != null) { for (int i = 0; i < personalApartment.imageUrl.length; i++) { Reference storageReference = FirebaseStorage.instance .ref() .child('/apartment_images') .child(personalApartment.imageUrl[i]); await storageReferences.delete(); } } else { FirebaseFirestore.instance .collection('apartments') .doc(personalApartment.id) .delete(); apartmentDeleted(personalApartment); } FirebaseFirestore.instance .collection('apartments') .doc(personalApartment.id) .delete(); apartmentDeleted(personalApartment); print('images deleted'); }
问题原因定位
- 路径拼接错误(最核心原因):如果
personalApartment.imageUrl存储的是图片的完整下载URL(类似https://firebasestorage.googleapis.com/v0/b/xxx/o/apartment_images%2Fxxx.jpg?alt=media&token=xxx),直接把完整URL拼接到/apartment_images后,生成的引用路径会变成/apartment_images/https://xxx,完全匹配不到真实的存储对象。 - 变量拼写错误:代码中定义的引用变量是
storageReference(单数),调用删除时写的是storageReferences.delete()(多了s),如果运行时未报编译错误,说明操作的是其他未定义的引用对象,自然找不到对应文件。 - 路径斜杠兼容问题:
child('/apartment_images')的前导斜杠在新版本Firebase Storage中不会自动做相对路径解析,和后续拼接内容组合后可能出现路径层级错位。 - 原有逻辑冗余:Firestore文档删除逻辑在if分支内外重复执行,无实际意义还会增加不必要的调用。
修复后的代码
deleteApartments( PersonalApartment personalApartment, Function apartmentDeleted ) async { try { // 先删除对应存储的图片 if (personalApartment.imageUrl?.isNotEmpty ?? false) { for (final imageUrl in personalApartment.imageUrl) { // 直接从完整下载URL生成正确的对象引用,无需手动拼接路径 final storageReference = FirebaseStorage.instance.refFromURL(imageUrl); await storageReference.delete(); } } // 统一删除Firestore中的公寓文档 await FirebaseFirestore.instance .collection('apartments') .doc(personalApartment.id) .delete(); apartmentDeleted(personalApartment); print('删除操作完成'); } catch (e) { // 捕获异常避免未处理崩溃,可在此处添加错误提示逻辑 print('删除操作失败:$e'); } }
修复说明
- 改用
refFromURL直接从已存储的图片下载URL生成对象引用,从根源避免路径拼接错误,适配新版本Firebase Storage的路径规则 - 修复了原有变量拼写不一致的问题
- 优化空值判断逻辑,避免空数组导致的异常
- 移除重复的Firestore文档删除逻辑,统一在最后执行
- 新增try-catch捕获所有删除过程中的异常,避免未处理崩溃
内容的提问来源于stack exchange,提问作者anup davda
相关产品推荐
相关产品推荐

