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.
CodePudding user response:
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'
CodePudding user response:
You are getting that error because your return statement is inside of if condition, so it assumes that it can possibly never return a value (if all conditions fail). So this could be solution for you:
Exercise getExerciseByID(String exerciseId) {
// initialize some default value to return if all conditions fail
Exercise returnValue = Exercise();
for (var exercise in _exercises) {
if (exercise.id == exerciseId) {
// if found update your initial value with found one
returnValue = exercise;
// stop for loop after finding right value
break;
}
}
return returnValue;
}
CodePudding user response:
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);