Home > Mobile >  Addition of multiple student result assessment score in flutter
Addition of multiple student result assessment score in flutter

Time:08-14

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
}
]

CodePudding user response:

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

CodePudding user response:

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);
  • Related