How to return a uploading stream object from the funtion

Viewed 75

I am working on function that is used to upload an image on the firsbase storage. I want to update the status of progress bar to show how much left uploading. here is firebStorageManger class which has firebase storage dependency

class FirebaseStorageManager {
  final FirebaseStorage _firebaseStorage;
  FirebaseStorageManager(this._firebaseStorage,);

  Future<UploadTask?> uploadFile(XFile file, String ref,) async {
    String? _link;
    double _progress;
    try {
      Reference fireStorageRef = _firebaseStorage.ref().child(ref);
      final metadata = SettableMetadata(
          contentType: 'image/jpeg',
          customMetadata: {'picked-file-path': file.path});
      var _byte = await file.readAsBytes();
      var uploadTask = 
      fireStorageRef
          .putData(_byte, metadata);
      
      // update the progressbar  
      
      uploadTask  .snapshotEvents
          .listen((event) {        
        _progress =100*
            event.bytesTransferred.toDouble() / event.totalBytes.toDouble();
      });
      uploadTask.whenComplete(() async{
        _link = await uploadTask.snapshot.ref.getDownloadURL();
      });
      return uploadTask;
    } catch (e) {
      return null;
    }
  }
}

I have a variable progressbarValue in the controller class. I think it would be bad approach to inject controller into FirebaseStorageManager and then change the value.

I am calling uploadFile() funtion from the controller so so what I think the solution is I have to return stream object to the controller so that controller can listen it and update the progressbarValue. here is controller funtion

uploadStickerPackIcon(XFile file) async {
   
    String basename = path.basename(file.path);
    print('file path =${file.path}');

    var uploadTaskStream =    _firebaseStorageManager
        .uploadFile(file,'pack/${basename}.jpg');
    }

now logically I should have to listen the "uploadTaskStream" object in the controller class. but we can listen it directly, first I have to make it as stream.

var uploadTaskStream =    _firebaseStorageManager
            .uploadFile(file,'pack/${basename}.jpg').asStream();

But now it says

 Expected a value of type 'UploadTask?', but got one of type 'TaskSnapshot'

Problem: how to return an uploading object from the uploadFile() function in FilestorageManger class, which I can listen .

0 Answers
Related