我将图像上传到 firebase 存储,但在 firebase 存储中看不到图像

I upload an image to firebase storage but i can't see image in firebase storage

首先这是关于我的上传图片代码,我尝试了一次又一次地修复它,但没有用

Future uploadImageFile() async
  {
    String fileName = DateTime.now().millisecondsSinceEpoch.toString();
    StorageReference storageReference = FirebaseStorage.instance.ref().child("Chat Images").child(fileName);

    StorageUploadTask storageUploadTask = storageReference.putFile(imageFile);
    StorageTaskSnapshot storageTaskSnapshot = await storageUploadTask.onComplete;

    storageTaskSnapshot.ref.getDownloadURL().then((downloadUrl){
      
      imageUrl = downloadUrl;
      setState(() {
        isLoading = false;
        onSendMessage(imageUrl, 1);
      });
    }, onError: (error){
      setState(() {
        isLoading = false;
      });
      Fluttertoast.showToast(msg: "Error: " + error);
    });
  }

点击上传图片后,终端中的结果如下:

[VERBOSE-2:ui_dart_state.cc(209)] Unhandled Exception: type 'PlatformException' is not a subtype of type 'String'
#0      ChatScreenState.uploadImageFile.<anonymous closure> (package:telegramchatapp/Pages/ChattingPage.dart:726:47)
#1      _rootRunUnary (dart:async/zone.dart:1436:47)
#2      _CustomZone.runUnary (dart:async/zone.dart:1335:19)
#3      _FutureListener.handleError (dart:async/future_impl.dart:178:22)
#4      Future._propagateToListeners.handleError (dart:async/future_impl.dart:779:47)
#5      Future._propagateToListeners (dart:async/future_impl.dart:800:13)
#6      Future._completeError (dart:async/future_impl.dart:610:5)
#7      _completeOnAsyncError (dart:async-patch/async_patch.dart:276:13)
#8      StorageReference.getDownloadURL (package:firebase_storage/src/storage_reference.dart)
<asynchronous suspension>
      

我不知道该怎么办。

您在问题中显示的异常来自这一行:

Fluttertoast.showToast(msg: "Error: " + error);

这里的error不是字符串,不能拼接成字符串。你想要的是:

Fluttertoast.showToast(msg: "Error: " + error.toString());

或者:

Fluttertoast.showToast(msg: "Error: $error");

这将告诉您上传失败的根本原因是什么,这样您就可以解决这个问题。

我做了一个简单的功能来上传到适合我的 Firebase 存储:

storage.dart

  Future upload({required String ref, required File file}) async {
    return await FirebaseStorage.instance.ref(ref).putFile(file).catchError(
          (e) => Utils.log(
            e,
            type: LogType.error,
          ),
        );
  }

  Future<String> downloadURL({required String ref}) async {
    return await FirebaseStorage.instance.ref(ref).getDownloadURL().catchError(
          (e) => Utils.log(
            e,
            type: LogType.error,
          ),
        );
  }

这个Utils.log()只是一个记录器,如果你愿意,你可以使用Toast。这就是我的使用方式:

anywhere_else.dart:

  String ref = 'users/${Services.auth.currentUser()!.uid}/selfie.png';

  var upload = await Services.storage.upload(ref: ref, file: selfie);

  if (upload != null) {
    user.selfie = await Services.storage.downloadURL(ref: ref);
  }