Firebase Storage报object-not-found错误求助(附Flutter代码)
解决Firebase Storage的object-not-found错误
可能的原因及修复方案
1. currentUser同步延迟导致引用路径错误
在_uploadToStorage方法中,你直接使用firebaseAuth.currentUser!.uid构建存储引用,但刚通过createUserWithEmailAndPassword创建用户后,本地currentUser可能未完成同步,导致生成的存储引用指向错误路径,最终触发找不到对象的错误。
修复:
修改_uploadToStorage方法,直接接收注册时返回的用户UID作为参数:
// 调整_uploadToStorage,新增uid参数 Future<String> _uploadToStorage(File image, String uid) async { Reference ref = firebaseStorage .ref() .child('profilePics') .child(uid); // 使用注册返回的uid,避免currentUser同步延迟问题 UploadTask uploadTask = ref.putFile(image); TaskSnapshot snap = await uploadTask; String downloadUrl = await snap.ref.getDownloadURL(); return downloadUrl; } // 在registerUser中调用时传入cred.user!.uid String downloadUrl = await _uploadToStorage(image, cred.user!.uid);
2. pickImage方法存在空指针风险
当用户取消图片选择时,pickedImage为null,此时执行File(pickedImage!.path)会抛出空指针异常,可能导致后续上传的文件对象无效,进而引发存储操作错误。
修复:
在赋值前增加null判断,处理用户取消选择的场景:
void pickImage() async { final pickedImage = await ImagePicker().pickImage(source: ImageSource.gallery); if (pickedImage != null) { Get.snackbar('Profile Picture', 'You have successfully selected your profile picture'); _pickedImage = Rx<File?>(File(pickedImage.path)); } else { _pickedImage = Rx<File?>(null); Get.snackbar('Profile Picture', 'You canceled selecting profile picture'); } }
3. Firebase Storage规则限制
如果Storage规则未正确配置,可能导致上传操作被拒绝,文件未成功存储,进而获取下载URL时触发object-not-found错误。
检查并调整规则:
确保规则允许已认证用户上传自己的头像,示例规则如下:
rules_version = '2'; service firebase.storage { match /b/{bucket}/o { match /profilePics/{uid} { allow write: if request.auth != null && request.auth.uid == uid; allow read: if request.auth != null; } } }
4. 上传文件有效性验证
确认传入_uploadToStorage的文件对象真实存在,避免传入无效文件路径导致上传失败。
修复:
在上传前增加文件存在性检查:
Future<String> _uploadToStorage(File image, String uid) async { if (!await image.exists()) { throw Exception('Selected file does not exist'); } Reference ref = firebaseStorage .ref() .child('profilePics') .child(uid); UploadTask uploadTask = ref.putFile(image); TaskSnapshot snap = await uploadTask; String downloadUrl = await snap.ref.getDownloadURL(); return downloadUrl; }
内容的提问来源于stack exchange,提问作者Ankit Gupta
相关产品推荐
相关产品推荐

