arrays - 尝试在 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;
...
在此先感谢您的帮助!
解决方案
尝试将您的 onpressed 更改为以下内容:
onPressed: () {
if (isPostLiked) {
// add your firebase code
print('unlike');
} else {
// add your firebase code
print('like');
}
isPostLiked = !isPostLiked;
}
我在 dartpad 上尝试过,每次按下时都会改变变量。
推荐阅读
- javascript - 将数据动态推送到 Highmaps
- http-headers - Apple Watch 优化的电子邮件不起作用
- pytorch - 作为学习率调度程序的线性衰减(pytorch)
- javascript - 如何使用请求获取 Javascript 页面的完整 HTML 内容?
- python - 如何检查一个元素是否在子列表中,然后打印子列表
- json - Flutter 仅从响应中打印一个值
- cassandra - CassandraCQLUnit 给出空会话
- laravel - Laravel 推送器监听私人事件:错误 403 页面被禁止
- python - 在 TensorFlow2 中结合来自不同“网络”的梯度
- javascript - 如何在整个 div 上进行搜索过滤