flutter - 如何在 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),
),
],
);
}
解决方案
将其粘贴到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),
);
}
推荐阅读
- powershell - 如何验证 Invoke-RestMethod 以列出工件存储库
- javascript - 将额外参数传递给 ListItem onMouseOver 处理程序
- mysql - 如何修复 shell bash mysql 加载查询语法错误?
- python-3.x - Pandas 向前和向后填充不同的索引
- android - RuntimeException:java.lang.IllegalAccessException:无法从类 android.app.Instrumentation 访问类 TuserActivity
- vue.js - v-for 循环数据不会显示
- html - 如何让我的网格布局在 Safari 中工作
- python - 我怎样才能像坐标一样排列这个输出
- r - data.table 等效于 dplyr::%in% 使用 ! (非)运算符
- javascript - 反应获取请求返回一个空数组