所以我有一个以下类,它将 onPressed
作为一个可以为 null 的 prop:
class Class1 {
final Function? onPressed;
const Class1({ this.onPressed });
callMethod() {
if(onPressed != null) {
onPressed(); // Complains here
}
}
}
如您所见,我检查了 onPressed
是否为空。但是 dart 仍然抱怨这条消息The function can't be unconditionally invoked because it can be 'null'. (view docs) Try adding a null check ('!').
请帮帮我。
答案 0 :(得分:4)
尝试按照编译器的建议添加空检查 ('!')
class Class1 {
final Function? onPressed;
const Class1({this.onPressed});
callMethod() {
if (onPressed != null) {
onPressed!(); //Note: ! is added here
}
}
}