Reputation: 802
SCENARIO
I am getting the json data by using flutter_bloc
library pattern what i want to achieve is that i want to count/add the star
key numbers and divide by length of star
means get the average number of stars. Below is the json data and dart code till now what i did.
JSON Data
"feedbacks": [
{
"id": 1,
"comment": "Corporate Brand Supervisor",
"star": 1,
"createdAt": "2021-09-07T11:35:15.954Z",
"updatedAt": "2021-09-07T11:35:15.954Z",
"customerId": 10,
"branchId": 3
},
{
"id": 9,
"comment": "Principal Implementation Liaison",
"star": 1,
"createdAt": "2021-09-07T11:35:15.954Z",
"updatedAt": "2021-09-07T11:35:15.954Z",
"customerId": 1,
"branchId": 3
}
],
HomePage.dart
Row(
children: [
for (var i in data[index].feedbacks!)
Text(i!.star!.toString()),],), //Here expecting an average number of stars 1+1/2 = 1.5
Upvotes: 0
Views: 210
Reputation: 1715
If you want to only display the result (average) value of stars in a Text
widget, you can do this:
Text((data[index]['feedbacks']!.map<int>((feedback) => feedback['star'] as int).reduce((acc, curr) => acc + curr) / data[index]['feedbacks']!.length).toStringAsFixed(2))
This assumes that every entry in feedback
actually has a star
property since I'm dividing by the amount of entries in feedback
I also added toStringAsFixed(2)
to ensure that there a 2 decimals after the decimal point (might want to adjust that) instead of having a very long value in cases like 1/3
Upvotes: 2