0

I have a problem with my flutter application. I want to upload an image to firebase storage and get the URL but the getDownloadUrl method doesn't work. Here is my code :

import 'package:firebase_storage/firebase_storage.dart' as firebase_storage;

...

Future<String> addImage(File file, firebase_storage.Reference reference) async{
  firebase_storage.UploadTask task = reference.putFile(file);
  firebase_storage.TaskSnapshot snapshot = task.snapshot;
  String urlString = await snapshot.ref.getDownloadURL();
  return urlString;
}

I think it's because of the new version of firebase_storage(5.2.0)

killian
  • 55
  • 7

2 Answers2

3

You have to wait for the firebase to store the image then only call getUrl by using await. Similarly, check out this link:https://stackoverflow.com/a/52714376/5408464

   Future<String> addImage(File file, firebase_storage.Reference reference) async{
  final task = await reference.putFile(file);
  final urlString = await (await task.onComplete).ref.getDownloadURL().toString();
  return urlString;
}
Mayb3Not
  • 441
  • 4
  • 10
  • thank you for the answer but the onComplete method is no longer available with the new firebase_storage version. How can I replace it? – killian Dec 29 '20 at 16:53
  • @killian what do you mean? – Mayb3Not Dec 29 '20 at 16:54
  • It's not possible to use onComplete with "task" (because it's no longer available with the 5.2.0 version of firebase_storage). So is there an other way to wait for the firebase to store the image ? Without "onComplete" – killian Dec 29 '20 at 17:00
  • Dart analysis: The getter 'onComplete isn't defined for the type 'UploadTask'. – killian Dec 29 '20 at 17:05
  • 1
    @killian you dont need to use onComplete, just use await for it. Check our this link: https://stackoverflow.com/a/52714376/5408464. and btw someone downvoted me for something they dont know kinda sad ;( – Mayb3Not Dec 29 '20 at 17:06
  • thank you its working now !! And I'm really sorry for that, I wanted to upvote your answer and no downvote but I can't do it now. Excuse me.. You saved my problem – killian Dec 29 '20 at 17:29
  • @killian No problem, happy to help ;) – Mayb3Not Dec 30 '20 at 01:17
-1

We need to wait for the UploadTask to complete, as per the source code below:

Future<String> addImage(File file, firebase_storage.Reference reference) async{
  firebase_storage.UploadTask task = reference.putFile(file);
  String urlString = await (await task.whenComplete).ref.getDownloadURL().toString();
  await task.whenComplete(() async {
      urlString = await task.ref.getDownloadURL();
  }).catchError((onError) {
    print(onError);
  });
  return urlString;
}
Stefano Amorelli
  • 4,553
  • 3
  • 14
  • 30