6

Is it possible to add or delete elements to an existing array stored in a Firestore document instead of fetching the array, add the element locally and send it back to the store?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Tristan Bilot
  • 479
  • 5
  • 16

1 Answers1

11

Hopefully, yes.

You can append or remove an element using the method update() in combination with FieldValue.arrayUnion([element]) or FieldValue.arrayRemove([element]).

Example:

Future<void> appendToArray(String id, dynamic element) async {
  _firestore.collection(RootKey).doc(id).update({
    'myArrayField': FieldValue.arrayUnion([element]),
  });
}

Future<void> removeFromArray(String id, dynamic element) async {
  _firestore.collection(RootKey).doc(id).update({
    'myArrayField': FieldValue.arrayRemove([element]),
  });
}
Tristan Bilot
  • 479
  • 5
  • 16