I uploaded multiple images into FirebaseStorage then saved URL image into Firestore, but only one URL image save into firestore.
for (var img in _image) {
Reference firebaseStorage = FirebaseStorage.instance
.ref()
.child("images/${foldername}/${imagename}");
UploadTask uploadTask = firebaseStorage.putFile(img);
TaskSnapshot task = await uploadTask;
task.ref.getDownloadURL().then((value) {
FirebaseFirestore.instance.collection("items").doc(user.uid).set({
"item_name": item_name.text,
"item_description": item_description.text,
"item_price": item_price.text,
"typeofitem": currentvalueSelected,
"sizeofitem": FieldValue.arrayUnion([selectedsize]),
"images": FieldValue.arrayUnion([value])
});
});
}
Right now when the upload of an image is completed and you've gotten its download URL, you call FirebaseFirestore.instance.collection("items").doc(user.uid).set({...})
each time. Calling set()
like this replaces the existing contents of the document, so you end up with the common fields and then only the download URL of the last image to be done.
You'll want to separate two types of writes:
var docRef = FirebaseFirestore.instance.collection("items").doc(user.uid);
docRef.set({
"item_name": item_name.text,
"item_description": item_description.text,
"item_price": item_price.text,
"typeofitem": currentvalueSelected,
"sizeofitem": FieldValue.arrayUnion([selectedsize]),
});
for (var img in _image) {
Reference firebaseStorage = FirebaseStorage.instance
.ref()
.child("images/${foldername}/${imagename}");
UploadTask uploadTask = firebaseStorage.putFile(img);
TaskSnapshot task = await uploadTask;
task.ref.getDownloadURL().then((value) {
docRef.update({
"images": FieldValue.arrayUnion([value])
});
});
}
It is because you have called to set the document inside the for loop so the previous data gets overwritten after every iteration
You could use Future.wait
if your uploading a lot of images.
...
List<UploadTask> uploadImgToStorageFutures = [];
List<Future<String>> getImgUrlFutures = [];
for (var img in _image) {
Reference firebaseStorage = FirebaseStorage.instance
.ref()
.child("images/${foldername}/${imagename}");
UploadTask uploadTask = firebaseStorage.putFile(img);
uploadImgToStorageFutures.add(uploadTask);
}
await Future.wait(uploadImgToStorageFutures).then((tasks) => tasks.forEach((task) {
getImgUrlFutures.add(task.ref.getDownloadURL());
}));
await Future.wait(getImgUrlFutures).then((urls) =>
FirebaseFirestore.instance.collection("items").doc(user.uid).set({
"item_name": item_name.text,
"item_description": item_description.text,
"item_price": item_price.text,
"typeofitem": currentvalueSelected,
"sizeofitem": FieldValue.arrayUnion([selectedsize]),
"images": urls
}));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.