Dart null safety - Returning a none nullable type

657

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):

  1. Change return declaration to nullable type (jamesdlin) Exercise?
  2. Throw exception at the end instead of returning null
  3. 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);
Share:
657
Kitcc
Author by

Kitcc

Updated on January 03, 2023

Comments

  • Kitcc
    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
      Manishyadav about 2 years
      please can you mention your error!
    • jamesdlin
      jamesdlin about 2 years
      What should happen if exerciseId is not found? You have a few choices: A. Return null and make getExerciseByID return a Exercise? instead. B. Construct and return a sentinel Exercise object that represents an invalid result. C. throw an exception.
    • Kitcc
      Kitcc about 2 years
      Thanks @Manishyadav , I have added the Error text.