Bee
Bee

Reputation: 45

Flutter: How can delete from firebase an array of objects?

I have this list with user products and I want to delete a product on button clic. Products ara store in firebase inside user doc as a Map products:[nameProduct:'',owned:''] Can u help me to figure how to delete a prodruct?

List.generate(
          userData['products'].length,
          (index) => ListTile(
              contentPadding: const EdgeInsets.only(
                 right: 15,
                 left: 15,
                 top: 0,
              ),
              title: Text(
                       userData['products'][index]['nameProducts'],
                       style: const TextStyle(letterSpacing: 2.0)),
                       subtitle: Text(productOwnedFunction(userData, index)),
                       trailing: IconButton(
                                  icon: const Icon(CupertinoIcons.trash),
                                  onPressed: () async {
                                    try {
                                      await FirebaseFirestore.instance
                                          .collection('users')
                                          .doc(userData['uid'])
                                          .update(
                                        {
                                          'products':
                                              FieldValue.arrayRemove(
                                                  [index])
                                        },
                                      );
                                    } catch (e) {
                                      print(e);
                                    }
                                  },
                                ),
                              )),

Upvotes: 0

Views: 667

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598668

You can't remove an item from an array by its index in Firestore API.

If you know the entire object to remove (so know all fields), you can pass that entire object to FieldValue.arrayRemove().

If all you have is the index of the item to remove, you'll have to:

  1. Read the document from the database and get the array from it.
  2. Modify the array contents in your application code.
  3. Write the entire array back to the databae.

Upvotes: 2

Related Questions