9

I have a document with an array field in it.

How can I update the array?

In firebase functions, with typescript, I did something like this:

admin.firestore()
    .collection('friendships')
    .doc(caller.data["uid"])
    .update({
        friends: admin.firestore.FieldValue
            .arrayUnion({
                          friendDisplayName: snapshot.data["friendDisplayName"],
                          friendUid: snapshot.ref
                       })
    })

I cannot find any alternative with Flutter.. how can I do?

magicleon94
  • 4,887
  • 2
  • 24
  • 53
  • this didn't work - Firestore.instance.collection('friendships').document(caller.data["uid"]).updateData({ 'friends':{ 'friendDisplayName': snapshot.data["friendDisplayName"], 'friendUid': snapshot.ref } ? – anmol.majhail Oct 12 '18 at 06:25

2 Answers2

5

Something like this

firestore.instance.
    .collection('friendships')
    .document(caller.data["uid"])
    .updateData({
  friends: FieldValue.arrayUnion({
    friendDisplayName: snapshot.data["friendDisplayName"],
    friendUid: snapshot.ref
  })
});
Harish
  • 576
  • 1
  • 8
  • 21
  • what does caller.data retrieve? I'm new to dart and i'm struggling to update array in my Firebase –  Nov 01 '21 at 13:05
4

The solution I give you is when you use Transactions, but regardless of that, it works the same...

List<dynamic> list = List.from(documentSnapshot.data['uids']);
list.add(uid);
await documentTransaction.update(
  postRef,
  <String, dynamic>{
    'counter': documentSnapshot.data['counter'] + 1,
    'uids': list,
  },
);
Shi
  • 510
  • 1
  • 5
  • 16
Luis Meneses
  • 109
  • 7
  • The thing is that some times you don't have the ability to fetch the whole list and then add a new element. It would be nice if you could just add a new element to the existing array without fetching first – Panagiss Oct 10 '20 at 11:32