首页 > 解决方案 > 尝试在 Flutter 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 是一个布尔值,我最初将其设置为 false 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;
...

在此先感谢您的帮助!

标签: arraysflutterdartgoogle-cloud-firestorestream-builder

解决方案


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

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

我在 dartpad 上尝试过,每次按下时都会改变变量。


推荐阅读