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.
>Solution :
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:)