Reputation: 479
I can successfully upload the image but can't get the URL of the uploaded image Also with the recent changes in the methods, I would like to write a cleaner code than this.
try {
await FirebaseStorage.instance
.ref()
.child('user_image')
.child(authResult.user
.uid + //ref gives access to root cloud store , firebase manages all the tokens etc
'.jpg')
.putFile(image);
} on FirebaseException catch (e) {
print(e);
}
//Download the Url
String url = await FirebaseStorage.instance
.ref()
.child('user_image')
.child(authResult.user
.uid + //ref gives access to root cloud store , firebase manages all the tokens etc
'.jpg')
.getDownloadURL();
print('Url' + url);
Upvotes: 0
Views: 1030
Reputation: 598668
You don't need to use an UploadTask
to get the download URL. A simpler version of your code is:
Reference ref = FirebaseStorage.instance .ref()
.child('user_image')
.child(authResult.user.uid+'.jpg')
try {
await ref.putFile(image);
String url = await ref.getDownloadURL();
print('Url' + url);
} on FirebaseException catch (e) {
print(e);
}
What I've done above:
StorageReference
, so that you only have to calculate it once and then both upload and get the download URL from that variable.getDownloadURL()
call, as you probably don't want to try and get the download URL when the upload fails.With these two changes, it's pretty idiomatic and really close to the FlutterFire documentation examples on uploading files and getting download URLs.
Upvotes: 1
Reputation: 1702
I use following code for uploading and downloading. You miss using uploadtask property.
final photoRef = FirebaseStorage.instance.ref().child("photos");
UploadTask uploadTask = photoRef.child("$id.jpg").putFile(photo);
String url = await (await uploadTask).ref.getDownloadURL();
Upvotes: 2