简体   繁体   中英

Flutter: How can use FieldValue.arrayRemove?

How can I delete an array of array of objects from Firestore? I want to delete it inside a list.generate

Here is my database structure, I want to delete [{street A, number 25}]

在此处输入图像描述

List.generate(
  ...
  IconButton(
    icon: const Icon(CupertinoIcons.trash),
    onPressed: () async {
      try {
        await FirebaseFirestore.instance
            .collection('users')
            .doc(data['uid'])
            .update(
          {
            'adress':
                FieldValue.arrayRemove(
                    ??)
          },
        );
      } catch (e) {
        print(e);
      }
    },
  ),
)),

As I see in your screenshot, the adress field is not of type array, it's a Map:

在此处输入图像描述

So there is no way you can call FieldValue.arrayRemove . If you want to remove that field, then please use the following lines of code:

Firestore.instance.collection('users').document(data['uid']).set(
    {'adress': FieldValue.delete()},
    SetOptions(
      merge: true,
    ),
)

Edit:

After you have updated the screenshot, now the adress field is indeed of type array:

在此处输入图像描述

If you want to delete a specific object from the array using FieldValue.delete() , you should use all the data in the object and not partial data . I have even written an article regarding updating an array of objects in Cloud Firestore:

Edit2:

In code it should look like this:

Firestore.instance.collection('users').document(data['uid']).update({
    'adress': FieldValue.arrayRemove(elementToDelete),
});

Please note that elementToDelete object should contain both fields populated. The number should hold the value of "25" and street should hold the value of "street A". It will not work if you use only one.

However, if you thought that Firestore provides a direct way to delete an array element by index, please note that is not possible. In such a case, you'll have to read the document, remove the element from the array, then write the document back to Firestore.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM