GAGAN SINGH
GAGAN SINGH

Reputation: 281

Problem in uploading url of current image to firestore database

When I upload FIRST image it gets store in Cloud Storage, but it doesn't store the image url in Firebase Firestore database, and when I upload the SECOND image it again get stores in cloud storage but in Firebase firestore database it stores the url of FIRST image and then again if I upload the THIRD image it gets store in cloud storage but it surprisingly upload the url of SECOND image in firebase firestore database and this goes so on. In short, it doesn't store the url of current image and on uploading the current image it uploads and display the previous one but if we check the cloud storage there are THREE images stored in it but in firestore database there are URL of only two images.I have tried both(update({"images": urls })) and (update({"images": FieldValue.arrayUnion(urls) })) as you can see I have commented the other one, both gives same result/problem. So, I don't know what is the reason for this? Pls help me out and thanks in advance. Here is the code below of uploading..

  _uploadImages() async {
   _images.forEach((image) {
  if(image!=null) {
    var _ref = _stoarge.ref().child("images/" + basename(image.path));
    _ref.putFile(image).whenComplete(() async {
      String url = await _ref.getDownloadURL();

      print(url);
      urls.add(url);
      print(url);
    });
  }
});
print("uploading:"+urls.asMap().toString());
await  FirebaseFirestore.instance.collection("users")
  .doc(auth.currentUser.uid).update({"images": urls });
  //  .doc(auth.currentUser.uid).update({"images": FieldValue.arrayUnion(urls) });
 } 

Upvotes: 1

Views: 445

Answers (1)

Tarik Huber
Tarik Huber

Reputation: 7408

You have an async/await issue in your code. The forEach won't wait on async events inside and the whenCompleted is not awaited at all.

_uploadImages() async {
  for (var image in _images) {
    var _ref = _stoarge.ref().child("images/" + basename(image.path));
    await _ref.putFile(image);
    String url = await _ref.getDownloadURL();

    print(url);
    urls.add(url);
    print(url);
  }
  print("uploading:" + urls.asMap().toString());
  await FirebaseFirestore.instance
      .collection("users")
      .doc(auth.currentUser.uid)
      .update({"images": urls});
  //  .doc(auth.currentUser.uid).update({"images": FieldValue.arrayUnion(urls) });
}

Upvotes: 1

Related Questions