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?

1
  • this didn't work - Firestore.instance.collection('friendships').document(caller.data["uid"]).updateData({ 'friends':{ 'friendDisplayName': snapshot.data["friendDisplayName"], 'friendUid': snapshot.ref } ? Commented Oct 12, 2018 at 6:25

2 Answers 2

5

Something like this

firestore.instance.
    .collection('friendships')
    .document(caller.data["uid"])
    .updateData({
  friends: FieldValue.arrayUnion({
    friendDisplayName: snapshot.data["friendDisplayName"],
    friendUid: snapshot.ref
  })
});
Sign up to request clarification or add additional context in comments.

1 Comment

what does caller.data retrieve? I'm new to dart and i'm struggling to update array in my Firebase
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,
  },
);

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.