FieldValue arrayUnion and Cloud FireStore with Flutter

13,884

Solution 1

I have found a solution. Try this:

 Firestore.instance
.collection('YourCollection')
.document('YourDocument')
.updateData({'array':FieldValue.arrayUnion(['data1','data2','data3'])});

If it still doesn't work, try to update your Firebase.

First open a terminal fetched to your flutter project, then:

cd ios
pod update Firebase

This solution is only for mac users.

Solution 2

New FlutterFire Update 2021

With the newest FlutterFire update there where lots of updates at the API but thankfully it hasn't changed that much for this problem. I'm talking about the newest plugins of Firebase for Flutter and specifically every plugin that is compatible with the new firebase_core ^0.7.0. So the code looks similar:

FirebaseFirestore.instance
.collection("YourCollection")
.doc("YourDocument")
.update({
      "anArray": FieldValue.arrayUnion(["data", "to", "append"])
    });

Solution 3

The other way if you have List of objects

Future<void> updateUserNewGroup(List<Group> data , String id) {

    List<Map> list=new List();

    if(data !=null && data.isNotEmpty){
        data.forEach((grp){
            list.add(grp.toJson());
        });
    }


    return ref.document(id).updateData({"groups": FieldValue.arrayUnion(list)}) ;
}

Solution 4

this is the code I used and it worked like a charm!

                _firestore
                .collection('x')
                .document('xxxxxxxxxx')
                .updateData({
              'comments': FieldValue.arrayUnion([
       {'comment': "comment goes here", 'sender': "[email protected]"}
              ])
            });

Solution 5

Following up on the existing answers, if the field does not exist you can use a set & merge. This can save you from checking if the field exists or not.

Firestore.instance
  .collection('YourCollection')
  .document('YourDocument')
  .setData({
    'array':FieldValue.arrayUnion(['data1','data2','data3'])
  }, merge: true);
Share:
13,884
Hitesh Sultaniya
Author by

Hitesh Sultaniya

Full time iOS Developer by day and an aspiring python developer by night. Passionate photographer as well.

Updated on June 14, 2022

Comments

  • Hitesh Sultaniya
    Hitesh Sultaniya about 2 years

    I have cloud fire store object like this

    "TestCollection" : ["Test1","Test"]
    

    Now I want to update this array with FieldValue.arrayUnion because if element is same then i don't want to do anything but if it is not then I would like to add element

    docRef.updateData({"TestCollection":FieldValue.arrayUnion(["test"])})
    

    but this statement gives the error like object can not have nested array

    Can anyone please help or provide same kind of example to have look for syntax ?