Firebase-Dart:上传图片时出现明显的竞争情况

时间:2018-08-10 07:04:48

标签: firebase dart firebase-storage

使用task.onStateChanged检测上载成功的时间。不幸的是,上传完成后,firebase不会始终将状态设置为“成功”。 onStateChanged将收到最后一个事件,其中状态==“正在运行”和bytesTransferred == totalBytes。此事件之后,不再有其他事件推送到onStateChanged

我试图通过在bytesTransferred == totalBytes的情况下退出来解决此问题,但是当我调用时会导致竞争 await task.snapshot.ref.getDownloadURL();证明为bytesTransferred == totalBytes,但downloadUrl尚不存在!

除了轮询来检查URL是否存在之外,还有其他方法可以解决此问题吗?

代码:

 Future<String> uploadImg(File img) async {
    final task = await fb.storage().ref(PATH + img.name).put(img);
    await _monitor(task, IMG_TASK_NAME);
    final uri = await task.snapshot.ref.getDownloadURL();
    return uri.toString();
  }

 Future<void> _monitor(fb.UploadTask task, String taskName) {
    final completer =  Completer<bool>();
    task.onStateChanged.listen((fb.UploadTaskSnapshot snapshot) async {
      final state = snapshot.task.jsObject.snapshot.state;

      // fb doesn't always set state == 'success' when done :(
      final isComplete = snapshot.bytesTransferred == snapshot.totalBytes;

      if(state == 'success') {
        completer.complete();
      }
      else if(state == 'error') {
        completer.completeError(taskName);
      }
    });
    return completer.future;
  }

0 个答案:

没有答案