flutterfirebase-storagevideo-upload

How to track the uploading process on firebase with flutter?


I have this future function that will upload a video to firebase, I want to track this uploading process in percentage, so after the uploading process is completed, I will get the url.

Code

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);
    }
  }

Solution

  • You can get by listening to TaskSnapshot Stream.

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

    For more info: https://pub.dev/documentation/firebase_storage/latest/firebase_storage/StorageTaskSnapshot-class.html

    If you are using an older version of Firebase storage i.e snapshotEvents is not available.

    This should work for you.

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