Dart null safety - Returning a none nullable type
Solution 1
It is because you have implicit return null
here. If none of if
statements will be fulfilled, excersise
will not be returned, therefore ther result will be null.
Exercise getExerciseByID(String exerciseId) {
for (var exercise in _exercises) {
if (exercise.id == exerciseId) {
return exercise;
}
}
return null; //this is what it complains, that the result might be null while you declare non null response
}
Options (alternatives):
- Change return declaration to nullable type (jamesdlin)
Exercise?
- Throw exception at the end instead of returning
null
- Always return something - eg default value or 'nothing found value'
Solution 2
add return at the end of the method in case the if condition is not true.
or you can use simple firstWhere method like:
return _exercises.firstWhere((exercise) => exercise.id == exerciseId);
Kitcc
Updated on January 03, 2023Comments
-
Kitcc over 1 year
I am completely new to the new Dart Null Safety and am trying to convert one of my projects and learn it. I'm getting a little confused with one error I received on a function, where it is returning a type. Here is the code:
Exercise getExerciseByID(String exerciseId) { for (var exercise in _exercises) { if (exercise.id == exerciseId) { return exercise; } } }
The error I am receiving is as follows:
The body might complete normally, causing 'null' to be returned, but the return type, 'Exercise', is a potentially non-nullable type. (Documentation) Try adding either a return or a throw statement at the end.
I am wondering what should I be doing/ returning in this case? Any advice on this would be really helpful. Thanks so much.
-
Manishyadav about 2 yearsplease can you mention your error!
-
jamesdlin about 2 yearsWhat should happen if
exerciseId
is not found? You have a few choices: A. Returnnull
and makegetExerciseByID
return aExercise?
instead. B. Construct and return a sentinelExercise
object that represents an invalid result. C.throw
an exception. -
Kitcc about 2 yearsThanks @Manishyadav , I have added the Error text.
-