how to add or remove item to the the existing array in firestore ?

前端 未结 2 1649
梦毁少年i
梦毁少年i 2020-12-19 13:27

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_firesto

2条回答
  •  南笙
    南笙 (楼主)
    2020-12-19 13:57

    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, {
                    'upvoters': FieldValue.arrayRemove(['12345'])
                  });
                } else {
                  await tx.update(snapshot.reference, {
                    'upvoters': FieldValue.arrayUnion(['12345'])
                  });
                }
              });
    

    Hope it helps

提交回复
热议问题