我正在尝试在我的应用程序中构建的新闻提要中获得一个like/like按钮。我使用的是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;
...提前感谢您的帮助!
发布于 2020-08-11 14:54:02
尝试将onpressed更改为以下内容:
onPressed: () {
if (isPostLiked) {
// add your firebase code
print('unlike');
} else {
// add your firebase code
print('like');
}
isPostLiked = !isPostLiked;
}我在dartpad上试过,每次按下时变量都会改变。
https://stackoverflow.com/questions/63352721
复制相似问题