Issue
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);
}
},
),
)),
Solution
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:
- Read the document from the database and get the array from it.
- Modify the array contents in your application code.
- Write the entire array back to the databae.
Answered By - Frank van Puffelen
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.