Home > OS >  How to write data to array in firebase?
How to write data to array in firebase?

Time:06-14

How to write data to an array in Firebase?

I could upload multiple images to Firestore, but I need to write the data to postImages array.

I tried to use the below methods, but it didn't work and the app is crashing.

String postid = _firestore.collection('Posts').doc().id;
    await _firestore.collection('Posts').doc(postid).set({
      'description': description,
      'imageType': 'image',
      'location': getSub,
      'postImages': [],
      'postid': postid,
      'postimage': '',
      'profile_image': profImage,
      'publisher': uid,
    });
    for (int i = 0; i < _images.length; i  ) {
      var imageUrl = uploadMultiImageToStroage('Posts', _images[i], true);
      _arrImageUrl.add(imageUrl.toString());
      await _firestore.collection('Posts').doc(postid).update({
        'postImages': FieldValue.arrayUnion([_arrImageUrl]),
      });
    }

CodePudding user response:

You can upload all file first then update the database.

await Future.forEach(_images, (XFile image) async {
    var imageUrl = await uploadMultiImageToStroage('Posts', image, true);
    _arrImageUrl.add(imageUrl.toString());
});

await _firestore.collection('Posts').doc(postid).update({
    'postImages': FieldValue.arrayUnion([_arrImageUrl]),
  });
  • Related