0

In the Workout class below, I'd like to initialize avgCalorieBurn to be the average of calorie burn for each exercise inside that class. Is there a way to do this?

class Wourkout {
  List<Exercise> exercises;
  int? avgCalorieBurn;

  Wourkout({required this.exercises, this.avgCalorieBurn});
}

class Exercise {
  int calorieBurn;
  Exercise({required this.calorieBurn});
}

2 Answers 2

1

You can add a method to the constructor. As stated in here. Also, typo in Wourkourt => Workout

class Workout {
  List<Exercise> exercises;
  int? avgCalorieBurn; // or late int avgCalorieBurn;

  Workout({required this.exercises}) {
    int sum = 0;
    exercises.forEach((exercice) {
      sum += exercice.calorieBurn;
    });
    avgCalorieBurn = sum ~/ exercises.length; // Truncated integer division
  }
}

class Exercise {
  int calorieBurn;
  Exercise({required this.calorieBurn});
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks that's it!
1
class Wourkout {
  List<Exercise> exercises;
  double? avgCalorieBurn;

  Wourkout({required this.exercises}) 
    : avgCalorieBurn = exercises.length  == 0 
                     ? null
                     : exercises.map((e) => e.calorieBurn).reduce((a, b) => a + b) / exercises.length;
}

class Exercise {
  int calorieBurn;
  Exercise({required this.calorieBurn});
}

I changed the average to a double, because that is what you get as the average between integers.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.