How to get the download URL from firebase with flutter? - firebase

I would like to retrieve the Download URL of a private image in firbase storage.
Hi have tried many of the suggestions on the site, but all of them end up in the same result.
I have tried the following code:
getImageNow() async {
StorageReference ref =
FirebaseStorage.instance.ref().child("/1.jpg");
String url = (await ref.getDownloadURL()).toString();
return url;
}
It works when i print the url inside the function, but when i try to call print(getImageNow())to get the url, i just get "Instance of 'Future<dynamic>'"
UPDATE*************
In the end i am trying to get somthing like this:
return Image.network(
getImageNow(),
);
But i can not get it to work with async.

Since getImageNow() is asynchronous (as indicated by the async keyword), you will need to use await to make the calling code wait for the result:
print(await getImageNow())
What await does here is that it essentially unwraps the Future and is equivalent to:
getImageNow().then((value) => print(value));

this is how i upload and get the download url
this part is how i get image from picker
Future getImage() async {
var image = await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
_image = image;
print('Image Path $_image');
});
}
then i upload it
Future uploadPic(BuildContext context) async {
String fileName = basename(_image.path);
StorageReference firebaseStorageRef = FirebaseStorage.instance.ref().child(fileName);
StorageUploadTask uploadTask = firebaseStorageRef.putFile(_image);
StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
final String url = (await taskSnapshot.ref.getDownloadURL());
print('URL Is $url');
}
hope it will help someone

Related

How to get the url from Firebase Storage file?

I want to retrieve the URL of a Uint8List image from firebase storage. But I am not able to do that. It prints a snapshot, not the url. Please help.
my code:
void _storeSignature() async {
try {
final Uint8List? signature = await exportSignature();
final FirebaseStorage? storage = FirebaseStorage.instance;
final String? pictureUrl =
"signature/${DateTime.now().millisecondsSinceEpoch.toString()}.png";
final ref = storage!.ref().child(pictureUrl!);
final uploadTask = ref.putData(signature!);
final downurl = await uploadTask.whenComplete(() {
return ref.getDownloadURL();
});
final url = downurl.toString();
print(url);
} catch (e) {
rethrow;
}
}
You have to await for the URL when calling ref.getDownloadURL()
change
return ref.getDownloadURL();
into
return await ref.getDownloadURL();
The UploadTask class extends Future, so you can also use await there already:
await ref.putData(signature!);
final downurl = await ref.getDownloadURL();
final url = downurl.toString();

How to get a Stream of download url in firebase flutter

i want to create a stream of firebase storage download link for all the images
firebase_storage.FirebaseStorage storage =
firebase_storage.FirebaseStorage.instance;
firebase_storage.Reference ref =
storage.ref().child('images');
firebase_storage.ListResult result = await ref.listAll();
result.items.forEach((firebase_storage.Reference ref) async* {
print('Found file: $ref');
yield (await ref.getDownloadURL()).toString();
});
}
the snapshot data is null
if i create with future it seems to work when i add all the urls in a list and give to listview builder
but i cant get each string through stream
I've had problems with ForEach and await getDownloadUrl(). Try using a for loop instead.
for (Reference refin result.items) async* {
print('Found file: $ref');
yield (await getDownloadUrl().toString());
}
First thing first create a instance of FirebaseStorage
final _firestorage = FirebaseStorage.instance;
after then we need ref. for get image from storage.
final ref = _firestorage.ref().child('image');
and then we can create image's url.
var imageURL = await ref.getDownloadURL();
and try this.
print(imageURL);
if you wanna get this codes into fully method:
String getImageURL(){
final _firestorage = FirebaseStorage.instance;
final ref = _firestorage.ref().child('image');
var imageURL = await ref.getDownloadURL();
if(imageURL != null){
return imageURL;
}else{
print("Couldn't load image");
}
}
Also you can get this image with StreamBuilder or FutureBuilder etc. for get more about FirebaseStorage check it out this documentation

Flutter: How to get multi download url?

Future<List<dynamic>> uploadImage({List<File> images, String Key}) async {
List<dynamic> imagesUrls = [];
images.asMap().forEach((index, image) async {
final StorageReference storageReference = FirebaseStorage().ref().child(_getImagePathByHereKey(Key, index: index));
final StorageUploadTask uploadTask = storageReference.putFile(image);
});
return imagesUrls;
}
I want to get download url and put it to imagesUrls. But imagesUrls is empty. How to get download url?
https://pub.dev/documentation/firebase/latest/firebase/StorageReference-class.html
There's a method called getDownloadUrl() which returns a Future. I'm assuming that's what you're looking for. I think you use it like this:
List<dynamic> imagesUrls = images.asMap().entries.map((entry) async {
final StorageReference storageReference = FirebaseStorage().ref().child(_getImagePathByHereKey(Key, index: entry.key));
final StorageUploadTask uploadTask = storageReference.putFile(entry.value);
return await storageReference.getDownloadUrl();
}).toList();
return imagesUrls;
I think entries.map can't take an async method though so you might wanna use streams. Think you got it from here though.

How can I add a photoUrl to the current user?

In my app I choose an image with the image picker dart package (pub.dev link). Then I upload this image to Cloud Storage. I also can get the url from the database, but how can I add this url to the current user as photoUrl? How can I update the firebase user?
image picker code:
getImage(BuildContext context) async {
var image = await ImagePicker.pickImage(source: ImageSource.gallery);
if (image != null) {
cropImage(image);
_showDialog(context);
}
setState(() {
_image = image;
print("Image Path $_image");
});
}
upload code:
uploadPic(BuildContext context) async {
String fileName = basename(_image.path);
StorageReference firebaseStorageRef =
FirebaseStorage.instance.ref().child("profilbilder/" + fileName);
StorageUploadTask uploadTask = firebaseStorageRef.putFile(_image);
StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
// Photo URL
var dowurl = await (await uploadTask.onComplete).ref.getDownloadURL();
String url = dowurl;
setState(() {
print("Profile Picture uploaded");
});
}
You can use the FirebaseUser object to store a user's profile photo's url.
Refer here: Manage users.
And Firebase getUrl

Upload multi images to firestore using flutter and get it's download URLs and save all of URLs to firebase

I have a form that have images to upload , when the user try to press on "Submit" button i'm trying to upload list of images to firestore and get all of its URLs and then submit a form to "x" collection in firebase but the writing on "x" collocation done before upload the images and get it's URLs.
I thinks the problem with (async,await).
Appreciate to help me.
List<File> imagePaths= new List() ;
List<String> imageURL= new List() ;
Future<FirebaseUser> getUser() async {
return await _auth.currentUser();
}
Future<void> uploadPic(File _image) async {
String fileName = basename(_image.path);
StorageReference firebaseStorageRef =
FirebaseStorage.instance.ref().child(Random().nextInt(10000).toString()+fileName);
StorageUploadTask uploadTask = firebaseStorageRef.putFile(_image);
var downloadURL = await(await uploadTask.onComplete).ref.getDownloadURL();
var url =downloadURL.toString();
imageURL.add(url); // imageURL is a global list that suppose to contain images URLs
print("\n ---------------------------\n downloadURL :"+ url);
print("\n ---------------------------\n imageURL :"+ imageURL.toString());
}
Submit(BuildContext context) {
//imagePaths is list of file
imagePaths.add(Front_image);
imagePaths.add(Back_image);
imagePaths.forEach((x) => {
uploadPic(x)
});
getUser().then((user) {
crudObj.addNew({
'uid': user.uid,
'name': name,
'images':imageURL,
}).then((result) {
Navigator.pop(context);
}).catchError((e) {
print(e);
});
});
}
You should call your Submit only once your upload task is complete. I would recommend implementing something like this:
Stream uploadImageToFirebaseStorage(File image, String fullPath) {
final StorageReference firebaseStorageRef =
FirebaseStorage.instance.ref().child(fullPath);
StorageUploadTask task = firebaseStorageRef.putFile(image);
return task.events;
}
And then listen to this Stream and only then submit:
uploadImageToFirebaseStorage(
image, 'path/imagename.jpg'
).listen((data) async {
StorageTaskEvent event = data;
if (data.type == StorageTaskEventType.success) {
String downloadUrl = await event.snapshot.ref.getDownloadURL();
await Submit(title, imageUrl: downloadUrl);
return true;
}
if (data.type == StorageTaskEventType.failure) return false;
});
Please take note that I did not re-write your code, I am sharing a possible implementation.

Resources