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

Flutter评论点赞功能报错:The method 'contains' was called on null

问题分析

错误The method 'contains' was called on null的核心原因有两个:

  1. 参数顺序完全错误:调用LikeComment时传入的参数顺序和方法定义的顺序不匹配,导致likes参数位置传入了非List类型的值(甚至可能是null)。
  2. 未处理likes字段为null的情况:Firestore中的评论文档可能没有初始化likes字段,或者数据加载时widget.snap['likes']尚未获取到值,导致调用contains方法时对象为null。
修复步骤

1. 修正LikeComment的调用参数顺序

方法定义的参数顺序是:postId → uid → likes → commentId,但你调用时顺序完全颠倒了,需要调整为正确的顺序:

await FirestoreMethods().LikeComment(
  widget.snap['postId'], // 第一个参数:postId
  myUid, // 第二个参数:uid
  widget.snap['likes'], // 第三个参数:likes
  widget.snap['commentId'], // 第四个参数:commentId
);

2. 处理likes为null的情况

在所有调用contains的地方,通过空合并运算符??给likes设置默认空数组,避免null调用方法:

2.1 UI代码中的修改

将所有widget.snap['likes'].contains(myUid)替换为(widget.snap['likes'] ?? []).contains(myUid):

Row(
  children: [
    LikeAnimation(
      isAnimating: (widget.snap['likes'] ?? []).contains(myUid),
      smallLike: true,
      child: IconButton(
        onPressed: () async {
          await FirestoreMethods().LikeComment(
            widget.snap['postId'],
            myUid,
            widget.snap['likes'],
            widget.snap['commentId'],
          );
        },
        icon: (widget.snap['likes'] ?? []).contains(myUid)
            ? const Icon(
                Icons.favorite,
                color: Colors.red,
              )
            : const Icon(
                Icons.favorite_border,
              ),
      ),
    ),
  ],
)

2.2 LikeComment方法中的修改

在方法内对传入的likes做null检查,同样用空合并运算符处理:

Future<void> LikeComment(String postId, String uid, List? likes, String commentId) async {
  try {
    // 处理likes为null的情况,默认使用空数组
    final currentLikes = likes ?? [];
    if (currentLikes.contains(uid)) {
      await _firestore.collection('posts').doc(postId).collection('comments').doc(commentId).update({
        'likes': FieldValue.arrayRemove([uid]),
      });
    } else {
      await _firestore.collection('posts').doc(postId).collection('comments').doc(commentId).update({
        'likes': FieldValue.arrayUnion([uid]),
      });
    }
  } catch (e) {
    print(e.toString());
  }
}

注意:这里把参数List likes改成List? likes,明确允许传入null,然后在内部处理成空数组。

3. 初始化Firestore评论文档的likes字段

为了从根源避免null问题,在创建评论文档时,确保likes字段默认设置为空数组[],比如创建评论的代码中:

await _firestore.collection('posts').doc(postId).collection('comments').add({
  // 其他字段...
  'likes': [], // 初始化空数组
});

这样后续所有评论都有likes字段,不会出现null的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 08:54:26