Home > other >  add string to an array in Firestore - flutter
add string to an array in Firestore - flutter

Time:09-03

i have created an array of strings "challengeMember" in Firestore database and i want to add data to it when user clicks a button, my database:

enter image description here

in my code am trying to update the array, every time user join a challenge, the challenge name will be added to this array i know how to access the array using:

FirebaseFirestore.instance.collection("Users").doc(user!.uid).update({'challengeMember': widget._challengeName});

but the problem with this it is not specifying the array index and it is not checking whether the index is empty or not, so how can i dynamically access this array and keep adding values.

CodePudding user response:

Firestore has a special trick to add an array, and it goes like this:

await FirebaseFirestore.instance.collection('users').doc(uid).update({
        'tokens': FieldValue.arrayUnion([token]),
      });

See the FieldValue documentation on how to manipulate arrays.

  • Related