首页 > 解决方案 > 如何在 Flutter 中获取没有“索引”的值

问题描述

如何获得平均星数(意味着结果应该得到 1.5)?注意:要获取的值没有索引,因为它不在 ListView.builder 下面是示例 json 代码,这就是我到目前为止所尝试的方式。

JSON

{
    "message": "feedbacks for restaurant branch returened",
    "data": [
        {
            "id": "4",
            "comment": "Investor Operations Coordinator",
            "star": 1,
        }
        {
            "id": "4",
            "comment": "Investor Operations Coordinator",
            "star": 2,
        }
    ]
 }

  Widget buildReviewNumbers(List<FeedbacksData> data) {
    return Column(
      children: [
        for (int index = 0; index < data.length; index++)
          Text(
            data[index].star.toString(),
            style: TextStyle(fontWeight: FontWeight.w900, fontSize: 30.0),
          ),
        
      ],
    );

}

标签: flutterdart

解决方案


将其粘贴到DartPad上

final map = {
  "message": "feedbacks for restaurant branch returened",
  "data": [
    {
      "id": "4",
      "comment": "Investor Operations Coordinator",
      "star": 1,
    },
    {
      "id": "4",
      "comment": "Investor Operations Coordinator",
      "star": 2,
    }
  ]
};


void main() {
  
  final data = map['data'] as List<Map<String, dynamic>>;
  
  var total = 0;
  
  data.forEach((e) {
    total += e['star'] as int;
  });
  
  print(total/ data.length);
}

对于您的情况:

Widget buildReviewNumbers(List<FeedbacksData> data) {
    var total = 0;
  
    data.forEach((e) {
      total += e.star;
    });

    return Text(
      '${total/data.length}',
      style: TextStyle(fontWeight: FontWeight.w900, fontSize:30.0),
    );
}

推荐阅读