You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter Firebase 帖子点赞系统如何获取并展示点赞总数

实现方案

方案1:基于现有存储结构实时获取点赞数

你当前的点赞数组存储逻辑可正常运行,只需用StreamBuilder监听对应帖子文档的实时变化,直接取like数组长度即可渲染到组件中,示例代码如下:

Widget buildLikeCount() {
  return StreamBuilder(
    stream: FirebaseFirestore.instance
        .collection("posts")
        .doc(widget.postId)
        .snapshots(),
    builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot) {
      if (!snapshot.hasData) {
        return const Text("0");
      }
      List<dynamic> likeList = snapshot.data!.get("like") ?? [];
      return Text(likeList.length.toString());
    },
  );
}

把上述组件放到需要展示点赞数的位置,只要点赞数据更新,组件会自动重绘,无需手动触发回调。

方案2:高并发场景优化方案(更实用的评分系统)

如果帖子点赞量可能超过数百,建议新增独立的likeCount数字聚合字段,避免每次拉取整个点赞数组浪费带宽和计算资源,调整后的逻辑如下:
点赞/取消点赞时同时更新数组和聚合字段,用Firebase事务保证数据一致性,避免并发更新导致计数错误,示例代码:

// 点赞/取消点赞通用方法
void togglePostLike() async {
  final String uid = FirebaseAuth.instance.currentUser!.uid;
  final DocumentReference postRef = FirebaseFirestore.instance.collection("posts").doc(widget.postId);

  await FirebaseFirestore.instance.runTransaction((transaction) async {
    DocumentSnapshot postSnapshot = await transaction.get(postRef);
    List<dynamic> likeList = postSnapshot.get("like") ?? [];
    int currentCount = postSnapshot.get("likeCount") ?? 0;

    if (likeList.contains(uid)) {
      // 已点赞,执行取消操作
      transaction.update(postRef, {
        "like": FieldValue.arrayRemove([uid]),
        "likeCount": currentCount - 1
      });
    } else {
      // 未点赞,执行点赞操作
      transaction.update(postRef, {
        "like": FieldValue.arrayUnion([uid]),
        "likeCount": currentCount + 1
      });
    }
  });
}

对应的展示组件可以直接监听likeCount字段,无需处理数组:

Widget buildLikeCount() {
  return StreamBuilder(
    stream: FirebaseFirestore.instance
        .collection("posts")
        .doc(widget.postId)
        .snapshots(),
    builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot) {
      if (!snapshot.hasData) {
        return const Text("0");
      }
      int count = snapshot.data!.get("likeCount") ?? 0;
      return Text(count.toString());
    },
  );
}

注意:首次上线需要给所有历史帖子的likeCount字段初始化,赋值为对应like数组的长度

内容的提问来源于stack exchange,提问作者Ru Ko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 10:36:06