0

When I add to a document using below code I will successfully be able to keep adding additional objects to the array, as long as I stay on the same screen.

  void createRecord(dataMap) async {
    _user = await FirebaseAuth.instance.currentUser();
    var createTransaction = (Transaction tx) async {
      var ds = await tx.get(db
          .collection('users')
          .document(_user.uid)
          .collection("days")
          .document(DateFormat("yyyy-MM-dd").format(dataMap['day'])));
      await tx.set(ds.reference, dataMap);
    };
    Firestore.instance.runTransaction(createTransaction);
  }

enter image description here

After navigating off the screen then back all objects are deleted when trying to add new ones. enter image description here

When I navigate back from a screen how can I add new objects to the collection with out deleting the old ones?

Thanks.

Matthew Simms
  • 49
  • 1
  • 1
  • 6

1 Answers1

1

To add a new, unique item to an array, you can use the arrayUnion operator.

Something like:

await tx.update(ds.reference, {
                'breakfast': FieldValue.arrayUnion(dataMap['breakfast'][0])
      });

Also see:

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