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

Flutter/Dart中如何计算列表数据平均值?获取美食评论平均评分

在Dart中计算美食评论的平均评分

嘿,这事儿在Dart里其实挺简单的,我给你分享两种实用的实现方式,再说说要注意的边界情况,你可以按需选择~

第一步:先定义Comment数据类

首先得把你提到的Comment类给定义出来,这样Dart才能识别列表里的对象结构:

class Comment {
  final int userId;
  final double rating;

  Comment({required this.userId, required this.rating});
}

方法一:基础循环实现(直观易读)

如果你喜欢逻辑清晰、容易理解的写法,用普通的for循环就很合适。思路就是先累加所有评论的评分,再除以评论的总数量:

double calculateAverageRating(List<Comment> comments) {
  // 初始化总评分和评论数
  double totalRating = 0.0;
  int commentCount = comments.length;

  // 遍历所有评论,累加评分
  for (var comment in comments) {
    totalRating += comment.rating;
  }

  // 计算平均评分(注意处理空列表)
  return commentCount == 0 ? 0.0 : totalRating / commentCount;
}

方法二:使用fold方法(简洁优雅)

如果你想让代码更紧凑,Dart的集合类提供了fold方法,可以帮我们一行完成累加操作,很符合Dart的函数式编程风格:

double calculateAverageRating(List<Comment> comments) {
  int commentCount = comments.length;
  if (commentCount == 0) return 0.0;

  // fold方法初始值为0.0,遍历每个评论累加评分
  double totalRating = comments.fold(0.0, (sum, comment) => sum + comment.rating);
  
  return totalRating / commentCount;
}

关键:处理空列表的边界情况

一定要注意!如果评论列表是空的,直接除以0会抛出IntegerDivisionByZeroException异常。上面两种方法里我都加了判断,空列表时返回0.0,你也可以根据需求改成返回null或者抛出自定义提示,比如:

double? calculateAverageRating(List<Comment> comments) {
  int commentCount = comments.length;
  if (commentCount == 0) return null; // 空列表返回null

  double totalRating = comments.fold(0.0, (sum, comment) => sum + comment.rating);
  return totalRating / commentCount;
}

怎么调用?

比如你有这样的评论列表:

void main() {
  List<Comment> comments = [
    Comment(userId: 1, rating: 4.5),
    Comment(userId: 2, rating: 4.0),
    Comment(userId: 3, rating: 3.5),
    Comment(userId: 4, rating: 3.0),
  ];

  double average = calculateAverageRating(comments);
  print('平均评分:$average'); // 输出:平均评分:3.75
}

两种方法都能得到正确结果,基础循环适合刚接触Dart的朋友,fold方法更简洁,看你习惯哪种啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:11:06