I am trying to delete a specific item from a database given only its element values. However, I keep getting the error message "The type 'Stream<QuerySnapshot<Object?>>' used in the 'for' loop must implement Iterable" over the items.snapshot() section. What am I doing wrong there, because I thought that it would get me all the snapshots of the documents? The deleteName, Type, and Location are all String variables that I defined earlier
CollectionReference items = FirebaseFirestore.instance.collection('items');
Object deleteUser() {
// Call the user's CollectionReference to add a new user
if (name != "" && type != "" && location != "") {
for (var doc in items.snapshots()) {
if (doc.data['name'] == deleteName &&
doc.data['type'] == deleteType &&
doc.data['location'] == deleteLocation) {
doc.delete();
}
}
return items;
} else {
return "There was a null error";
}
}
CodePudding user response:
Your code is a little confusing, if your getting items from Firestore
, you will want to map it to an object for iterating through.
Item(
String id; //Give an id value for document ID in firestore
String name;
String type;
String location;
);
//Get Items
CollectionReference itemsCollection = FirebaseFirestore.instance.collection('items');
List<Item> items = itemsCollection.snapshots().map(itemsSnapshot)
//Map Items
List<Item> itemsSnapshot(QuerySnapshot snapshot) {
return snapshot.docs.map((DocumentSnapshot doc) {
Map<String, dynamic> data = doc.data() as Map<String, dynamic>;
return Item(
id: doc.reference.id, //this is your reference to firestore
name: data['name'],
type: data['type'],
location: data['location'],
);
}).toList();
}
//Iterate through list of items
for(Item item in items){
//do any checks you want here
if(item.name == "Nobody"){
//delete document
itemsCollection.doc(item.id).delete();
}
}
CodePudding user response:
Your items
is a CollectionReference
object, and calling snapshots()
returns a Stream
, which is you can't loop over with a for loop.
My guess is that you're looking to use get
instead of snapshots
, so that you can then await
the result and process it:
CollectionReference itemsCol = FirebaseFirestore.instance.collection('items');
var itemsSnapshot = await itemsCol.get();
for (var doc in itemsSnapshot.docs) {
...
}