尽管存在空检查,但 Dart 空安全性会抱怨函数变为空

时间:2021-03-07 08:20:48

标签: flutter dart

所以我有一个以下类,它将 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 ('!').请帮帮我。

1 个答案:

答案 0 :(得分:4)

尝试按照编译器的建议添加空检查 ('!')

class Class1 {
  final Function? onPressed;

  const Class1({this.onPressed});

  callMethod() {
    if (onPressed != null) {
      onPressed!(); //Note: ! is added here
    }
  }
}