Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore: add or remove elements to existing array with Flutter [duplicate]

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?

like image 255
Tristan Bilot Avatar asked Sep 07 '26 19:09

Tristan Bilot


1 Answers

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]),
  });
}
like image 97
Tristan Bilot Avatar answered Sep 11 '26 03:09

Tristan Bilot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!