0

I am using Firebase Database for my mobile application that I developed with Flutter. I want to add a new array to this database. I am adding my data to a list. These data contain the same values. When I use the FieldValue.arrayUnion(stats) code, only elements with different values are added.

The list I made contains the following values; [0-0-0-0 , 0-0-0-0 ,0-0-0-0 ,0-0-0-0 ]. value of saved firebase is just 0-0-0-0.

Firebase database saves when the values are different.

When I add through the firebase site, there is no problem, but when I do it with flutter, I encounter the above mentioned saving problem. Can you help me? Thanks.

    for(int i = 0; i < 3;i++)
    {
        stats.add("0-0-0-0");
    }

      FirebaseFirestore.instance
          .collection("xxxx")
          .doc(auth.currentUser!.uid)
          .collection("xxxxx")
          .doc(xxxxx)
          .set({
        "Lang_1": FieldValue.arrayUnion(xxxxx),
        "Lang_2": FieldValue.arrayUnion(xxxxx),
        "Length": counter,
        "Stats": FieldValue.arrayUnion(stats),
      });

my solution.

  stats.clear();
  for (int i = 0; i < 3; i++) {
    stats.add("0-0-0-0");
  }
  final docData = {
    "x": x,
    "x": x,
    "x": x,
    "Stats": stats,
  };

  FirebaseFirestore.instance
      .collection("x")
      .doc(x)
      .collection("x")
      .doc(x)
      .set(
        docData,
      );

1 Answers1

0

That's the expected behavior: arrayUnion treats the array contents as a set, and only adds the item if it isn't already present.

There is no arrayAdd operator, so if you want to add a duplication, you will have to:

  1. Read the document in your application code
  2. Add the item to the array
  3. Write the entire array back to the database.

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807