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

Flutter读取Firebase评论时出现函数调用错误的问题求助

Flutter读取Firebase评论时出现函数调用错误的问题求助

嗨,我一眼就看出问题所在啦!这个错误的根源其实是你对Map类型的取值写法搞错了,咱们来一步步解决:

错误原因

你从Firebase文档里取出的commentData是一个Map<String, dynamic>对象,而你现在用了圆括号()**来取值(比如commentData("CommentText")),但圆括号是用来调用函数的,Map的正确取值方式应该是**方括号[]`,这就是系统提示"The expression doesn't evaluate to a function, so it can't be invoked here"的原因——你把一个Map当成函数来调用了,当然会报错啦!

解决方法

只需要把所有用圆括号取值的地方改成方括号就行,另外为了避免空值问题,还可以加上空值合并运算符??给个默认值,确保不会因为字段缺失导致崩溃。

修改后的核心代码片段如下:

return Comment(
  text: (commentData["CommentText"] ?? "").toString(),
  user: commentData["CommentedBy"] ?? "",
  time: formatDate(commentData["CommentTime"] ?? Timestamp.now()),
);

完整的StreamBuilder修改后代码

StreamBuilder<QuerySnapshot>(
  stream: FirebaseFirestore.instance
      .collection('news')
      .doc(widget.postId)
      .collection('comments')
      .orderBy("CommentTime", descending: true)
      .snapshots(),
  builder: (context, snapshot) {
    if (!snapshot.hasData) {
      return const Center(
        child: CircularProgressIndicator(),
      );
    }
    return ListView(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      children: snapshot.data!.docs.map((doc) {
        final commentData = doc.data() as Map<String, dynamic>;
        return Comment(
          text: (commentData["CommentText"] ?? "").toString(),
          user: commentData["CommentedBy"] ?? "",
          time: formatDate(commentData["CommentTime"] ?? Timestamp.now()),
        );
      }).toList(),
    );
  },
)

额外提示

如果你的formatDate函数需要特定的类型(比如Firebase的Timestamp),记得确保commentData["CommentTime"]的类型匹配,用?? Timestamp.now()可以在字段缺失时给一个默认的时间,避免函数调用出错。

备注:内容来源于stack exchange,提问作者Ibrahim Mansour

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.22 11:08:14