Flutter dart update array in Firestore

Viewed 1199

I have a problem with my code. I want to update an array in my Firestore database but this method doesn't work. I want rewrite the array every time: this code doesn't work:

List<LineupModel> newLineup = List<LineupModel>();
var playerInField1 = LineupModel(playerId: 850, position: "0-0");
var playerInField2 = LineupModel(playerId: 870, position: "1-0");
newLineup.add(playerInField1);
newLineup.add(playerInField2);
FirebaseFirestore.instance.collection("users").doc("123").update({"lineup": []});
FirebaseFirestore.instance.collection("users").doc("123").update({"lineup": FieldValue.arrayUnion(newLineup)});

If I write the object directly, the update work correctly.

FirebaseFirestore.instance.collection("users").doc("123").update({"lineup": FieldValue.arrayUnion([{"playerId": 850, "position": "0-0"}, {"playerId": 870, "position": "1-0"}])});

This code also does not work

FirebaseFirestore.instance.collection("users").doc("123").update({"lineup": newLineup});

thanks a lot!

1 Answers

I have a way to solved this problem. I think you cant directly passed a List of Array on arrayUnion (not sure). The way I solved this, is to iterate the list and store them one by one. Theres also a batch upload like my example

      newLineup.forEach((value) async {
        await FirebaseFirestore.instance.collection("users").doc("123").set({
          "lineup": FieldValue.arrayUnion([
            value, //Make sure this is Map<String, dynamic> so that firestore can read it
          ])
        }, SetOptions(merge: true));
      });
Related