How can I increment a value from firebase?

Viewed 4355

I'm trying to elaborate a function where when the icon is pressed the firebase number would increment by 1, when the icon was pressed again it would increment by -1 and it would show de total of likes returning as a "Text().toString()". I'm trying to use "FieldValue.increment" but unfortunately the number has not being increased on firebase. What am I doing wrong? thanks in advance for your help!

class LanchonetesContact extends StatefulWidget {
final DocumentSnapshot lanchonetes;

LanchonetesContact(this.lanchonetes);

@override
 _LanchonetesContactState createState() => 
 _LanchonetesContactState();
}

class _LanchonetesContactState extends State<LanchonetesContact> {

bool liked = false;

 _pressed() {
 setState(() {
  liked = !liked;
      });
  }

 @override
 Widget build(BuildContext context) {
   return Scaffold(
    appBar: AppBar(
      leading: IconButton(
          icon: Icon(Icons.arrow_back),
          onPressed: () {
          Navigator.pop(context);
          }),
    title: Text("Lanchonetes"),
    centerTitle: true,
    backgroundColor: Colors.purple[900],
    actions: <Widget>[
      IconButton(
          icon: Icon(
 liked ? Icons.favorite : Icons.favorite_border, 
 color: Colors.white,) ,
          onPressed: () {
            _pressed();
if(liked){
Firestore.instance.collection('lanchonetes')
.document("")
.updateData({"likes": FieldValue.increment(1)});

}else {

Firestore.instance.collection('lanchonetes')
.document("")
.updateData({"likes": FieldValue.increment(-1)});
            }
          }
      )],
    ),
 Padding(
      padding: EdgeInsets.only(top: 3.0),
      child: Card(
          elevation: 1.0,
          child: GestureDetector(
            child: Container(
              height: 100.0,
              width: 500.0,
              color: Colors.white,
              child: Padding(
                padding: EdgeInsets.symmetric(
                    vertical: 30.0, horizontal: 15.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Icon(Icons.favorite, color: Colors.black,),
                  Text(widget.lanchonetes.data["likes"].toString()),
                  ],
                ),
              ),
            ),
            onTap: () {

            },
          )),
    ),
2 Answers

I don't see what document you are trying to update. You need the document reference.

Update: FieldValue.increment works just fine and is the shortest way to do it.

// Get document reference
final DocumentReference docRef = Firestore.instance.collection("lanchonetes").document(REPLACE_WITH_ID);
docRef.updateData({"likes": FieldValue.increment(1)});

Another way is to create a transaction for it:

final TransactionHandler transactionHandler = (Transaction tran) {
   tran.get(docRef).then((DocumentSnapshot snap) {
      if (snap.exists) {
         tran.update(docRef, <String, dynamic>{'likes': snap.data['likes'] + 1});
          // update state by calling _pressed() or anything else you like

        }
      });
    }; 
Firestore.instance.runTransaction(transactionHandler);

This would be your like() method, for dislike() you obviously replace snap.data['likes'] + 1 with snap.data['likes'] - 1

After sometime I returned to this same situation and after some research I was able to find an answer. I just needed to specify my document as "widget.lanchonetes.documentId", so the firebase would read the data according to the document I choose and it was not necessary to specify it.

Firestore.instance.collection('lanchonetes')
.document(widget.lanchonetes.documentId)
.updateData({"likes": FieldValue.increment(1)});
Related