代码之家  ›  专栏  ›  技术社区  ›  Kitcc

Dart null安全性-返回不可为空的类型

  •  0
  • Kitcc  · 技术社区  · 4 年前

    我对新的Dart零安全性完全陌生,正在尝试转换我的一个项目并学习它。我对我在函数中收到的一个错误感到有点困惑,它返回了一个类型。以下是代码:

    Exercise getExerciseByID(String exerciseId) {
    for (var exercise in _exercises) {
      if (exercise.id == exerciseId) {
        return exercise;
      } 
    }
    }
    

    我收到的错误如下:

    正文可能会正常完成,导致返回“null”,但返回类型“Exercise”可能是不可为null的类型。(文档)尝试在末尾添加return或throw语句。

    我想知道在这种情况下我应该做什么/返回?任何关于这方面的建议都会非常有用。非常感谢。

    3 回复  |  直到 4 年前
        1
  •  0
  •   Antoniossss    4 年前

    这是因为你有 return null 在这里如果没有 if 声明将得到履行, excersise 不会返回,因此结果将为空。

    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
    }
    

    备选方案:

    1. 将返回声明更改为可为null的类型(jamesdlin) Exercise?
    2. 在末尾抛出异常,而不是返回 null
    3. 总是返回一些东西-例如默认值或“未找到任何值”
        2
  •  0
  •   Ante Bule    4 年前

    之所以会出现这种错误,是因为return语句在if条件中,所以它假设它可能永远不会返回值(如果所有条件都失败)。所以这可能是你的解决方案:

    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;
      }
    
        3
  •  0
  •   mohmdezeldeen    4 年前

    如果if条件不为true,则在方法末尾添加return。

    也可以使用简单的firstWhere方法,如:

    return _exercises.firstWhere((exercise) => exercise.id == exerciseId);