Search code examples
flutterdartdart-null-safety

Dart null safety - Returning a none nullable type


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.


Solution

  • 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'