0

There is a response from an API that looks like this snippet below, i would like to add the values (student scores over a period of time) and display the total value in the text widget on the UI

data : [
{
score : 10
}

{
score: 34
}

{
score: 45
}
]
namdi
  • 73
  • 1
  • 10

2 Answers2

0

You can use a foreach loop to add all values like the example

void main() {

  List data = [
    {"score": 10},
    {"score": 34},
    {"score": 45}
  ];

  int totalScore = 0;

  data.forEach((value) {
    totalScore += value['score'] as int;
  });

  print(totalScore); // Output 89
}

Output: 89

OMi Shah
  • 5,768
  • 3
  • 25
  • 34
Kaushik Chandru
  • 15,510
  • 2
  • 12
  • 30
0

As for the List<Result>? results; you can fold the assessments

 final result = Result(assessments: [
    Assessment(id: "1", score: 10),
    Assessment(id: "2", score: 34)
  ]);

  int total = result.assessments?.fold(0,
          (previousValue, element) => (element.score ?? 0) + previousValue!) ??
      0;

  print(total);
Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56