Reputation: 45
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
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:
Upvotes: 2