body_might_complete_normally
函式體可能正常完成,導致返回 'null',但返回型別 '{0}' 是一個可能非空的型別。
描述
#當方法或函式返回型別是可能非空,但控制流到達函式末尾時會隱式返回 null,分析器會生成此診斷資訊。
示例
#以下程式碼會生成此診斷資訊,因為方法 m 在方法末尾隱式插入了 null 返回,但該方法宣告為不返回 null
dart
class C {
int m(int t) {
print(t);
}
}以下程式碼會生成此診斷資訊,因為方法 m 在方法末尾隱式插入了 null 返回,但由於類 C 可以用非空型別引數例項化,該方法實際上被宣告為不返回 null
dart
class C<T> {
T m(T t) {
print(t);
}
}常見修復方法
#如果可以返回一個合理的值,請在方法末尾新增一個 return 語句
dart
class C<T> {
T m(T t) {
print(t);
return t;
}
}如果方法不會到達隱式返回,請在方法末尾新增一個 throw
dart
class C<T> {
T m(T t) {
print(t);
throw '';
}
}如果方法有意在末尾返回 null,請在方法末尾新增一個顯式的 return null,並更改返回型別使其可以返回 null
dart
class C<T> {
T? m(T t) {
print(t);
return null;
}
}