Home > database >  Flutter how to add map to existing array on firebase
Flutter how to add map to existing array on firebase

Time:11-08

I am using this code to upload data to firebase:

List<Map<String, dynamic>> mapData = [
    {
      'name': 'name1',
      'done': false,
      'frequency': '1',
    },
    {
      'name': 'name2',
      'done': false,
      'frequency': '5',
    },
  ];

if (isExist == false && listNameController.text.isNotEmpty) {
        await Firestore.instance
            .collection(widget.user.uid)
            .document(listNameController.text.toString().trim())
            .setData({
          'users': mapData,
        });

enter image description here

But now I want to add more data. I have tried this code but it overwrites all content. What can I do to just add the data to 'users'?

Firestore.instance
.collection(widget.user.uid)
.document(widget.currentList.keys.elementAt(widget.i))
.updateData({
'users': {
'name': 'name3',
'done': false,
'frequency': '7'
},

enter image description here

CodePudding user response:

You can use arrayUnion to add array elements.Please use the latest version of firestore package from pub.dev

Firestore.instance
.collection(widget.user.uid)
.document(widget.currentList.keys.elementAt(widget.i)).update({
          "users": FieldValue.arrayUnion([new User]),
 });
  • Related