简体   繁体   中英

increment firebase field value in flutter?

I have a problem with that code below.

I want to create a blog app and I want to let people like posts and when someone clicks the like button it

should increase the field value in firebase and if he clicked again it decrements the value.

My Code: -


bool liked = false;

------------------

onPressed: () async {
          await Firestore.instance
              .collection('posts')
              .document('${widget.uid}')
              .updateData(
            {
              "likes": FieldValue.increment(
                (liked ? (-1) : (1)),
              ),
            },
          );
          setState(() {
            liked = !liked;
          });
        },

Seems like your liked value go back to false even after the setState. Did you check liked before updating data. And could you show us exactly where do you declare your variable.

From your code it just seems like everytime you click the value of 'liked' is false. That makes your code to just increment the value by one. You have to check if the user has liked the post before and then change the state for the 'liked' bool.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM