我的应用从Firebase存储获取图像。如果没有图像,我希望能够处理该错误。但是我似乎无法正常工作。
我尝试过尝试捕获。
我已经尝试过了
Future<dynamic> getImage(int index){
return FirebaseStorage.instance.ref().child(widget.snap[index].data['英文品名']+".jpg").getDownloadURL().catchError((onError){
print(onError);
});
}
还有这个
Future<dynamic> getImage(int index){
var imageStream;
try {
imageStream = FirebaseStorage.instance.ref().child(widget.snap[index].data['英文品名']+".jpg").getDownloadURL();
} catch (e) {
print(e);
}
return imageStream;
}
但是我总是遇到未处理的异常错误,我的应用程序崩溃了。
E/StorageException(11819): StorageException has occurred.
E/StorageException(11819): Object does not exist at location.
E/StorageException(11819): Code: -13010 HttpResult: 404
E/StorageException(11819): StorageException has occurred.
E/StorageException(11819): Object does not exist at location.
E/StorageException(11819): Code: -13010 HttpResult: 404
E/StorageException(11819): { "error": { "code": 404, "message": "Not Found. Could not get object", "status": "GET_OBJECT" }}
E/StorageException(11819): java.io.IOException: { "error": { "code": 404, "message": "Not Found. Could not get object", "status": "GET_OBJECT" }}
如何处理此异常? Image of exception in VS Code
答案 0 :(得分:1)
根据图片的大小,上传文件需要不同的时间。所以很可能你的错误是因为 async 和 await 的错误组合。此代码适用于我。
Future<String> uploadSingleImage(File file) async {
//Set File Name
String fileName = DateTime.now().millisecondsSinceEpoch.toString() +
AuthRepository.getUser().uid +
'.jpg';
//Create Reference
Reference reference = FirebaseStorage.instance
.ref()
.child('Single Post Images')
.child(fileName);
//Now We have to check status of UploadTask
UploadTask uploadTask = reference.putFile(file);
String url;
await uploadTask.whenComplete(() async {
url = await uploadTask.snapshot.ref.getDownloadURL();
});
print('before return');
return url;
}
答案 1 :(得分:0)
抛出错误是因为您试图在尚未创建的时间访问下载 url。
您可以将上传代码封装在 if 语句中,如下例所示。这样可以保证上传任务成功完成。
if(storageRef
.child(folderName)
.putFile(fileName).isSuccessful)
{
url = await storage.child("folderName").child(fileName).getDownloadURL();
}