我對新的 Dart Null Safety 完全陌生,并且正在嘗試轉換我的一個專案并學習它。我對在函式上收到的一個錯誤感到有些困惑,它回傳一個型別。這是代碼:
Exercise getExerciseByID(String exerciseId) {
for (var exercise in _exercises) {
if (exercise.id == exerciseId) {
return exercise;
}
}
}
我收到的錯誤如下:
主體可能正常完成,導致回傳“null”,但回傳型別“Exercise”是潛在的不可為空的型別。(檔案)嘗試在末尾添加 return 或 throw 陳述句。
我想知道在這種情況下我應該做什么/回傳?對此的任何建議都會非常有幫助。非常感謝。
uj5u.com熱心網友回復:
這是因為你在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
}
選項(備選方案):
- 將回傳宣告更改為可空型別 (jamesdlin)
Exercise? - 最后拋出例外而不是回傳
null - 總是回傳一些東西 - 例如默認值或“沒有找到值”
uj5u.com熱心網友回復:
您收到該錯誤是因為您的 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;
}
uj5u.com熱心網友回復:
如果 if 條件不成立,則在方法末尾添加 return。
或者您可以使用簡單的 firstWhere 方法,例如:
return _exercises.firstWhere((exercise) => exercise.id == exerciseId);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/431593.html
上一篇:FlutterTextfield捕獲美元金額并收取費用
下一篇:未定義名稱“Firestore”
