'FLUTTER and FIREBASE: How to increment an int in a map?
I use flutter + firebase and I have a problem, in my db I have a 'Votes' value that is an array of 2 int. I want to increment them using like this : 'Votes': [FieldValue.increment(nb1), FieldValue.increment(nb2)], but it is not working, so I'm stuck I don't know how to increment them.
Future vote(String voteid) async {
List<dynamic> listvote = [];
List<dynamic> vote1 = [];
List<dynamic> vote2 = [];
List<dynamic> votevierge = [];
var vote = nomines.indexOf(voteid);
int nb1 = 0;
int nb2 = 0;
final snapShot =
await Firestore.instance.collection('rooms').document(pincode).get();
if (snapShot != null) {
listvote = snapShot.data['Votes'];
vote1 = snapShot.data['Vote1'];
vote2 = snapShot.data['Vote2'];
listvote[vote] = listvote[vote] + 1;
if (vote == 0) {
votevierge = List.from(vote1);
votevierge.add(nameid);
nb1 = 1;
} else {
votevierge = List.from(vote2);
votevierge.add(nameid);
nb2 = 1;
}
vote++;
Firestore.instance.collection('rooms').document(pincode).updateData({
'Votes': [FieldValue.increment(nb1), FieldValue.increment(nb2)],
'Vote$vote': votevierge,
});
}
}
Solution 1:[1]
You can increment the value of a field by .set() method with Setoptions().
For example, i have a map of question in the firebaseFirestore and i want to increment the value of 'upVotes' key by 1 then :
FirebaseFirestore.instance.collection('questions').doc(questionId).set({
'question' : {
'upVotes' : FieldValue.increment(1),
},
// This option helps in merging with initial data
SetOptions(merge:true),
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Narayan Poudel |

