I'm trying to save records in the cloud firestore using flutter. The thing is that it only adds one element and keeps updating its values whenever I add a new one through the app.
Here is my code:
Future addInterventionToDB(String userId, String etat, String op, String iv) {
return FirebaseFirestore.instance
.collection("interventions")
.doc(userId)
.set({
'etat': etat,
'operateur': op,
'intervention': iv,
'userId': user!.uid
});
}
and here is the function used in the UI part!
String etatLabel = "";
String operateur = "";
String intervention = "";
addIntervention(String etatt, String op, String iv) async {
String currentUser = FirebaseAuth.instance.currentUser!.uid;
if (currentUser != null) {
DatabaseMethods().addInterventionToDB(currentUser, etatt, op, iv);
}
}
and here is the button where I did the call of the method:
onPressed: () async {
await addIntervention(etatLabel, operateur, intervention);
},
Noting that the values are extracted from chips (selected value of each chip). I don't know what's wrong in here, tried updating the state of the variables each time a new selection takes place, but still having the same issue.
CodePudding user response:
Since you passed the userId
as the doc id, it keeps on overwriting it.
Replace
return FirebaseFirestore.instance
.collection("interventions")
.doc(userId)
.set({
'etat': etat,
'operateur': op,
'intervention': iv,
'userId': user!.uid
});
with
return FirebaseFirestore.instance
.collection("interventions")
.add({
'etat': etat,
'operateur': op,
'intervention': iv,
'userId': user!.uid
});
But in this case, it adds random doc id. So you cannot fetch with userId
. But you are already adding the userId
as a field inside the document with this line 'userId': user!.uid
. So you can fetch with that.
Hope it helps! Happy coding:)
CodePudding user response:
The code is correct but since you might be using the same UID the data is being overwritten in the collection. Refer to this site for more insight about using firestore. Hope this helps. Happy Coding :)
CodePudding user response:
This is happening because you are setting .doc(userId).set({})
the data (read more here). What you have to do is let firebase auto-generate unique uids for every document added. Check out a modified version of your code
Future addInterventionToDB(String userId, String etat, String op, String iv) {
return FirebaseFirestore.instance
.collection("interventions")
.doc()
.set({
'etat': etat,
'operateur': op,
'intervention': iv,
'userId': user!.uid
});
}
to read the data of a particular userId,
final query = FirebaseFirestore.instance
.collection("interventions").where("userId", isEqualTo:user!.uid).get();