Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do update array values in Flutter cloud_firestore?

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?

like image 903
magicleon94 Avatar asked Oct 09 '18 19:10

magicleon94


2 Answers

Something like this

firestore.instance.
    .collection('friendships')
    .document(caller.data["uid"])
    .updateData({
  friends: FieldValue.arrayUnion({
    friendDisplayName: snapshot.data["friendDisplayName"],
    friendUid: snapshot.ref
  })
});
like image 95
Harish Avatar answered Nov 09 '22 18:11

Harish


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,
  },
);
like image 4
Luis Meneses Avatar answered Nov 09 '22 19:11

Luis Meneses