0
votes

I have followed this tutorial https://www.youtube.com/watch?v=HCmAwk2fnZc and got everything working with regards to upload/crop/etc but I need to be able to get the imageURL after the image has completed uploading. I have seen examples online where the whole upload is async and then you can just wait for the URL with the code below, however, this example doesn't do the upload async... which I am new to this but I assume it is because they show the percentage upload.

I am trying to call the below but I am getting the error "A value of type 'Future' can't be assigned to a variable of type 'String'."

  Future getImageURL() async {
    StorageReference ref = FirebaseStorage.instance.ref().child("/$docID");
    var url = (await ref.getDownloadURL()).toString();
    return url;
  }

String imageURL;
imageURL = getImageURL();

The upload is started via:

  StorageUploadTask _uploadTask;

  void _startUpload(){
    String filePath = '$docID';

    setState(() {
      _uploadTask = _storage.ref().child(filePath).putFile(widget.file);
    });

  }

Then there is a StreamBuilder which uses the _uploadTask, which within this, on the .isComplete I want to be able to call for the image URL.

StreamBuilder<StorageTaskEvent>(
      stream: _uploadTask.events,
      builder: (context, snapshot) {
        var event = snapshot?.data?.snapshot;

        double progressPercent = event != null ? event.bytesTransferred / 
event.totalByteCount : 0;

        if (_uploadTask.isComplete){             

        }

I need to know how to call the async function once the file is uploaded (_uploadTask.isComplete) and then wait to get the DownloadURL.

Any advice would be great!

Thanks!

1

1 Answers

1
votes

When using Futures to extract data, using an await in front of the fucntion when you call it lets the app know that the function is an asynchronous function, and it should wait for it to complete.

String imageURL = await getImageURL();

The code below is for accessing the download url in a StreamBuilder

StreamBuilder(
      stream: _uploadTask.events,
      builder: (BuildContext context, snapshot) {
          final StorageTaskEvent event = snapshot.data;
          final StorageTaskSnapshot snap = event.snapshot;
          double progressPercent = (event.bytesTransferred / event.totalByteCount) ?? 0;
          String downloadUrl = snap.ref.getDownloadURL();
        
      },
    );