尝试在Flutter Streambuilder中构建“喜欢/不喜欢”按钮-不起作用

问题描述

我正在尝试在我的应用程序中构建的新闻源中获得“喜欢/不喜欢”按钮。我正在使用streambuilder。

这是按钮的代码

FlatButton(
                              child: Container(
                                child: Column(
                                  children: <Widget>[
                                    Icon(
                                      Icons.thumb_up,color: Colors.black,),Text(
                                      'Like',style: TextStyle(fontSize: 12.0),],onpressed: isPostLiked == true ? () {
                                _firestore.collection('posts').document(postID).updateData({'likeCount' : postLikeCount - 1,'likedBy' : FieldValue.arrayRemove(['${loggedInUser.email}'])});


                                isPostLiked = false;
                                print('USER HAS UNLIKED THIS POST');

                              } : () {
                                _firestore.collection('posts').document(postID).updateData({'likeCount' : postLikeCount + 1,'likedBy' : FieldValue.arrayUnion(['${loggedInUser.email}'])});

                                isPostLiked = true;
                                print('USER HAS LIKED THIS POST');

                              },

isPostLiked是一个布尔值,我最初将其设置为假bool isPostLiked = false;

我遇到的问题是它只让用户喜欢发布。它不会让用户与帖子不同。似乎它只是没有更新isPostLiked = true,而这似乎正是我要绞尽脑汁的地方。有什么想法吗?

有关更多上下文,这是FlatButton嵌套在其中的Streambuilder小部件的一些代码

StreamBuilder<QuerySnapshot>(
              stream: _firestore
                  .collection('posts')
                  .orderBy('date',descending: true)
                  .snapshots(),builder: (context,snapshot) {
                if (!snapshot.hasData) {
                  return Center(
                    child: CircularProgressIndicator(
                      backgroundColor: Colors.lightBlueAccent,);
                }
                final posts = snapshot.data.documents;
                List<Widget> postWidgets = [];
                for (var post in posts) {
                  bool isPostLiked = false;
...

在此先感谢您的帮助!

解决方法

尝试将您的onpress更改为以下内容:

onPressed: () {
      if (isPostLiked) {
        // add your firebase code
        print('unlike');
      } else {
        // add your firebase code
        print('like');
      }
      isPostLiked = !isPostLiked;
    }

我在dartpad上进行了尝试,并使其每次按下时都会更改该变量。