简体   繁体   English

增加 flutter 中的 firebase 字段值?

[英]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.应该增加 firebase 中的字段值,如果他再次单击它会减小该值。

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.即使在 setState 之后,您liked的值 go 也似乎恢复为 false。 Did you check liked before updating data.你在更新数据之前检查过liked吗? 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.您必须检查用户之前是否喜欢过该帖子,然后将 state 更改为“喜欢”布尔值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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