5

Firestore has recently add the new new method FieldValue.arrayUnion(value) and FieldValue.arrayRemove(value) but i couldn't find the implementation in flutter cloud_firestore package. Is there any way to achieve this result ?

Firestore addUpdate: https://firebase.google.com/docs/firestore/manage-data/add-data#update_elements_in_an_array

2 Answers 2

11

Here is the simple example to show how to update the array values. My document have an up voters array to add the user id's who have up-votes the document.

configure firestore, the config details can be copied form your google-services.json file

   final FirebaseApp app = await FirebaseApp.configure(
    name: 'test',
    options: const FirebaseOptions(
      projectID: 'projid',
      googleAppID: 'appid',
      apiKey: 'api',
      databaseURL: 'your url',
    ),
  );
  final Firestore firestore = Firestore(app: app);

  await firestore.settings(timestampsInSnapshotsEnabled: true);

update code using transaction

fireStore.runTransaction((Transaction tx) async {
            DocumentSnapshot snapshot =
                await tx.get(widget._document.reference);
            var doc = snapshot.data;
            if (doc['upvoters'].contains('12345')) {
              await tx.update(snapshot.reference, <String, dynamic>{
                'upvoters': FieldValue.arrayRemove(['12345'])
              });
            } else {
              await tx.update(snapshot.reference, <String, dynamic>{
                'upvoters': FieldValue.arrayUnion(['12345'])
              });
            }
          });

Hope it helps

Sign up to request clarification or add additional context in comments.

Comments

5

Update: And now it seems that it is supported! With the version 0.8.0.

https://pub.dartlang.org/packages/cloud_firestore

And then use FieldValue.arrayUnion and FieldVale.arrayRemove.


There doesn't seems to be a way currently. Please follow the following two github issues:

https://github.com/flutter/flutter/issues/21148 https://github.com/flutter/flutter/issues/20688

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.