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 ?
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.
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.
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.
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"])
});
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)}) ;
}
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);
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]"}
])
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With