如何使用flutter跟踪Firebase上的上传过程?

问题描述

我有这个将来的功能,可以将视频上传到Firebase,我想按百分比跟踪此上传过程,所以在完成上传过程后,我将获得网址。

代码

Future storageupload() async {
    try {
      if (controller = null) {
        dialog('Error','Please Provide A Video Name',() => {});
      } else {
        StorageReference ref = FirebaseStorage.instance
            .ref()
            .child("Khatma 1")
            .child("Videos")
            .child(controller.text != null ? controller.text : "");
        StorageUploadTask uploadTask = ref.putFile(
            File(Variables.lastVideoPath),StorageMetadata(contentType: 'video/mp4'));
      }
    } catch (e) {
      print(e);
    }
  }

  Future uploadToStorage() async {
    try {
      await storageupload();
      final downloadUrl = await FirebaseStorage.instance
          .ref()
          .child("Khatma 1")
          .child('Videos')
          .child(controller.text)
          .getDownloadURL();

      final String url = downloadUrl.toString();

      print(url);
    } catch (error) {
      print(error);
    }
  }

解决方法

您可以收听TaskSnapshot流。

uploadTask.snapshotEvents.listen((TaskSnapshot snapshot) {
      double _progress = snapshot.bytesTransferred.toDouble() / snapshot.totalBytes.toDouble();
    });

有关更多信息:https://pub.dev/documentation/firebase_storage/latest/firebase_storage/StorageTaskSnapshot-class.html

如果您使用的是较旧版本的Firebase存储,即snapshotEvents不可用。

这应该对您有用。

uploadTask.events.listen((event) {
  double _progess = event.snapshot.bytesTransferred.toDouble()  / event.snapshot.totalByteCount.toDouble();
});