Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FieldValue arrayUnion and Cloud FireStore with Flutter

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 ?

like image 719
Hitesh Sultaniya Avatar asked Sep 14 '18 13:09

Hitesh Sultaniya


People also ask

What is cloud firestore flutter?

Read Data. Cloud Firestore gives you the ability to read the value of a collection or a document. This can be a one-time read, or provided by realtime updates when the data within a query changes.

How do I add a Map to an array in flutter?

Create a new Map in Dart/Flutter For example, HashMap map = HashMap<int, String>() is accepted. We can create a new LinkedHashMap using Map constructor like this. Map map = Map<int, String>(); if (map is LinkedHashMap) { print("This is a LinkedHashMap."); } // Result: This is a LinkedHashMap.


5 Answers

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.

like image 76
Djiveradjane Canessane Avatar answered Oct 04 '22 01:10

Djiveradjane Canessane


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"])
    });
like image 24
Panagiss Avatar answered Oct 04 '22 02:10

Panagiss


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)}) ;
}
like image 27
Marshall Takudzwa Chabanga Avatar answered Oct 04 '22 01:10

Marshall Takudzwa Chabanga


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);
like image 22
gieoon Avatar answered Oct 04 '22 00:10

gieoon


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]"}
              ])
            });
like image 45
CHANDUKA SAMARASINGHE. Avatar answered Oct 04 '22 02:10

CHANDUKA SAMARASINGHE.