如何处理Firebase存储StorageException

Tra*_*is 6 dart firebase flutter firebase-storage

我的应用程序从 Firebase 存储获取图像。如果不存在图像,我希望能够处理该错误。但我似乎无法让它发挥作用。

\n\n

我尝试过用 try catch 包围。

\n\n

我试过这个

\n\n
Future<dynamic> getImage(int index){\n      return FirebaseStorage.instance.ref().child(widget.snap[index].data[\'\xe8\x8b\xb1\xe6\x96\x87\xe5\x93\x81\xe5\x90\x8d\']+".jpg").getDownloadURL().catchError((onError){\n        print(onError);\n      }); \n }\n
Run Code Online (Sandbox Code Playgroud)\n\n

和这个

\n\n
 Future<dynamic> getImage(int index){\n   var imageStream;\n   try {\n       imageStream = FirebaseStorage.instance.ref().child(widget.snap[index].data[\'\xe8\x8b\xb1\xe6\x96\x87\xe5\x93\x81\xe5\x90\x8d\']+".jpg").getDownloadURL();    \n   } catch (e) {\n     print(e);\n   }\n   return imageStream;\n }\n
Run Code Online (Sandbox Code Playgroud)\n\n

但我总是遇到未处理的异常错误并且我的应用程序崩溃。

\n\n
E/StorageException(11819): StorageException has occurred.\nE/StorageException(11819): Object does not exist at location.\nE/StorageException(11819):  Code: -13010 HttpResult: 404\nE/StorageException(11819): StorageException has occurred.\nE/StorageException(11819): Object does not exist at location.\nE/StorageException(11819):  Code: -13010 HttpResult: 404\nE/StorageException(11819): {  "error": {    "code": 404,    "message": "Not Found.  Could not get object",    "status": "GET_OBJECT"  }}\nE/StorageException(11819): java.io.IOException: {  "error": {    "code": 404,    "message": "Not Found.  Could not get object",    "status": "GET_OBJECT"  }}\n
Run Code Online (Sandbox Code Playgroud)\n\n

如何处理此异常?\n VS Code 中的异常图像

\n

小智 2

根据图像的大小,上传文件将花费不同的时间。因此,您的错误很可能是由于 async 和 wait 的错误组合造成的。这段代码对我有用。

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;
  }
Run Code Online (Sandbox Code Playgroud)