I'm stuck trying to test my code. but I get the error that "The return type 'Null' isn't a 'University', as required by the closure's context.
Any suggestions on how to fix this?
Here's the code:
static Future<void> deleteFaculty(String universityCode, String facultyCode) async {
University? targetUniversity = _universities.firstWhere(
(uni) => uni.code == universityCode,
orElse: () => null, // doesn't work.
);
if (targetUniversity != null) {
int initialLength = targetUniversity.faculties.length;
targetUniversity.faculties.removeWhere((f) => f.code == facultyCode);
int finalLength = targetUniversity.faculties.length;
if (finalLength < initialLength) {
await saveUniversities(_universities); // Await saving universities after modification
} else {
throw Exception('Faculty $facultyCode not found in university ${targetUniversity.name}');
}
} else {
throw Exception('University $universityCode not found');
}
}`
I will appreciate any solutions guys
Assuming _universities
is of type Iterable<University>
, you can use the firstWhereOrNull
extension method instead.
Alternatively, you can do something like this:
University? targetUniversity = _universities.cast<University?>().firstWhere(
(uni) => uni!.code == universityCode,
orElse: () => null,
);