user14789593
user14789593

Reputation:

How to add an array item to a document Firestore Flutter

I would like to add (or create if first) an array of map like this in my document:

videos
 - 0
  - url : myurl
 - 1
  - url : another one

by console I can do this, by I don't know how to do in code. This is my current set method:

await databaseReference.collection("${mycol}").doc("${mydoc}")
        .set({
          'url': url,
        });

and this adds a simple string to database. How Could I do this add an item in that structure I mentioned early?

Update

And what if I have this :

videos
 - 0
  - url : myurl
  - name : myname
 - 1
  - url : another one
  - name : myname

Upvotes: 0

Views: 1662

Answers (2)

Deepak Lohmod
Deepak Lohmod

Reputation: 2272

You can add array by:-

List<Map> videos=[
    {
      'url':'url',
      'name':'Harry',
    },
    {
      'url':'url',
      'name':'John',
    }
  ];
    await databaseReference.collection("${mycol}").doc("${mydoc}")
            .set({
              'url': FieldValue.arrayUnion([videos]),
            });

Now, if you have added 3 elements and in future wanna add 4th one then:-

List<Map> new=[
{
'url':'url for 4th video',
'name':'4th person name',
},
];
await databaseReference.collection("${mycol}").doc("${mydoc}")
                .update({
                  'url': FieldValue.arrayUnion([videos]),
                });

The purpose of FielValue.arrayUnion is that it automatically adds the new data to the firebase i.e. now you will have 4 elements in the array (3 previously added and 1 recently added).

Upvotes: 1

Caleb Robinson
Caleb Robinson

Reputation: 1120

You can do this in a similar way to what you are doing right there. For example:

await _firestore.collection(mycol).document(mydoc)
  .setData({
    'videos': arrayOfUrls,
    // OR
    'videos': mapOfUrls
  });

Firebase supports arrays and maps out of the box!

Upvotes: 1

Related Questions