getGrades method Null safety

Future<Map<String, List<CourseGrade>>> getGrades()

Retrieves grades of the currently signed in student and its corresponding courses, grouped by management.

Throws an exception if some request fails.

Implementation

Future<Map<String, List<CourseGrade>>> getGrades() async {
  final response = await _gradesProvider.requestGrades();
  if (response.statusCode != 200) {
    throw Exception(response.reasonPhrase);
  }

  final json = jsonDecode(response.body) as Map<String, dynamic>;
  final courseGradesJson = json['grades'] as List<dynamic>;

  final gradesMap = <String, List<CourseGrade>>{};

  for (final item in courseGradesJson) {
    final itemParsed = item as Map<String, dynamic>;
    final courseId = itemParsed['courseId'] as int;
    final courseResponse = await _subjectsProvider.requestSubject(courseId);
    final course = Course.fromJson(jsonDecode(courseResponse.body));

    final courseGrade =
        CourseGrade.fromJson(itemParsed).copyWith(course: course);

    gradesMap.putIfAbsent(course.management, () => []);
    gradesMap[course.management]?.add(courseGrade);
  }

  return gradesMap;
}