Flutter Firestore Run Transaction to make your UpVoting counter with FieldValue.arrayUnion

 Code:

import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

var myDocId, numberOfUpVoters;

void addUpVotingField() async {
List<String> emptyList = new List();
await FirebaseFirestore.instance.collection('YourCollection').add({
"OtherField": "OtherValue",
//... more fields
"upVoters":
FieldValue.arrayUnion(emptyList), //to store uid of users who up-voted
}).then((DocumentReference documentReference) {
myDocId = documentReference.id;
});
}

void firestoreTransaction() {
User user = FirebaseAuth.instance.currentUser;

DocumentReference documentReference =
FirebaseFirestore.instance.collection('YourCollection').doc(myDocId);

FirebaseFirestore.instance.runTransaction((transaction) async {
DocumentSnapshot documentSnapshot =
await transaction.get(documentReference);

if (documentSnapshot.data()['upVoters'].contains(user.uid)) {
transaction.update(documentReference, <String, dynamic>{
'upVoters': FieldValue.arrayRemove([user.uid])
});
} else {
transaction.update(documentReference, <String, dynamic>{
'upVoters': FieldValue.arrayUnion([user.uid])
});
}
}).then((value) async {
await FirebaseFirestore.instance
.collection("YourCollection")
.doc(myDocId)
.get()
.then((doc) {
setState(() {// should run inside stateful widget
numberOfUpVoters = doc['upVoters'].length;
});
});
});
}


Comments

Popular posts from this blog

Android CameraX Picture And Video Capture Complete Code Tutorial

Flutter: call a method from another class / setState a page from outside that class with StreamController

How To Add AdMob To Flutter App Quick Tutorial