【问题标题】:Flutter - returning UploadTask returns TaskSnapshot insteadFlutter - 返回 UploadTask 而是返回 TaskSnapshot
【发布时间】:2020-10-28 13:59:31
【问题描述】:

自上次flutter升级Flutter 1.22.2

  Future uploadImageToStore(path, {String remotePath = "receiptImages"}) async {
    Io.File _image = Io.File(path);
    String fileName = Path.basename(_image.path);
    print("uploadImageToStore " + path);
    if (await _image.exists()) {
      final Reference storageReference =
          FirebaseStorage.instance.ref().child(remotePath + "/" + fileName);
      final UploadTask uploadTask = storageReference.putFile(_image);

      return uploadTask;
    } else {
      print("image does not exit");
    }
  }

它不返回UploadTask,而是返回TaskSnapshot

使用此方法的代码使用UploadTask 设置监听器:

final UploadTask uploadTask = await this.uploadImageToStore(
    newReceipt['mergedImgPath']['path'],
    remotePath: "receiptMergedImage");

uploadTask.events.listen((event) async {
  this.updateReceiptProgress(event, newReceipt.key, receiptBloc);
});

以前版本的代码,现在可以编译但抛出运行时异常:

Unhandled Exception: type 'TaskSnapshot' is not a subtype of type 'UploadTask'

如何解决此问题以使用新的颤振版本?

【问题讨论】:

    标签: flutter


    【解决方案1】:

    这是我的解决方案:

    将uploadImageToStore 更改为:

      Future<TaskSnapshot> uploadImageToStore(path,
          {String remotePath = "receiptImages", void onData(event)}) async {
        Io.File _image = Io.File(path);
        String fileName = Path.basename(_image.path);
        print("uploadImageToStore " + path);
        if (await _image.exists()) {
          final Reference storageReference =
              FirebaseStorage.instance.ref().child(remotePath + "/" + fileName);
          final UploadTask uploadTask = storageReference.putFile(_image);
          uploadTask.events.listen(onData);
    
          return uploadTask;
        } else {
          print("image does not exit");
        }
      }
    

    即添加onData参数并将其用于uploadTask.events.listen(onData);

    如下使用:

    final TaskSnapshot taskSnapshot = await this.uploadImageToStore(
        newReceipt['mergedImgPath']['path'],
        remotePath: "receiptMergedImage", 
        onData: (event) async {
          this.updateReceiptProgress(event, newReceipt.key, receiptBloc);
        });
    

    虽然它解决了问题,但我仍然不确定为什么原始代码停止工作

    【讨论】:

      【解决方案2】:

      对我有用的是改变:

      return uploadTask;
      

      到

      return Future.value(uploadTask);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-11-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-05
        • 2021-06-11
        • 2021-02-21
        相关资源
        最近更新 更多