I want to check if a user has a string ’Level' with any number in his document.
Level: int
If this is the case, the future should return true and false if not. That’s the code I’m trying it with:
class StufenService{
String userID;
StufenService(this.userID);
final CollectionReference userTodos =
FirebaseFirestore.instance.collection('userTodos');
Future checkIfStufeExists() async {
await userTodos.where('Stufe' is int).get();
final data = QuerySnapshot.data.documents.where(userID);
if (data.exists){
return true;
} else
{return false;}
}
}
First I filter out all users who have ’Level': int in their firebased document. Then I want to check if the current user is among the users.
The data after the QuerySnapshot is underlined in red:
The getter 'data' isn't defined for the type 'QuerySnapshot'.
Can someone help me to implement my plan? Maybe the whole thing has to be done differently?
CodePudding user response:
For cases like this, I find it most useful to keep the FlutterFire documentation and Firestore reference handy. Based on those, you code should be something like:
final CollectionReference userTodos =
FirebaseFirestore.instance.collection('userTodos');
Future checkIfStufeExists() async {
var query = userTodos.where('Stufe', isEqualTo: 42); // First condition
query = query.where("userId", isEqualTo: userID); // Second condition
final querySnapshot = await query.get(); // Read from the database
return querySnapshot.size > 0; // Check if there are any results
}
CodePudding user response:
You are not doing anything with the returned value of the where statement. The class QuerySnapshot does not have .data static getter. In order to access the returned value from firestore you need to do something like that:
...
final snapshot = await userTodos.where('Stufe' is int).get();
final data = snapshot.data;
...