So I have a following class which takes onPressed
as a prop which can be null:
class Class1 {
final Function? onPressed;
const Class1({ this.onPressed });
callMethod() {
if(onPressed != null) {
onPressed(); // Complains here
}
}
}
As you can see I have a check if onPressed
is null. But dart still complains with this message The function can't be unconditionally invoked because it can be 'null'. (view docs) Try adding a null check ('!').
Please help me.
Use the null assertion operator ( ! ) to make Dart treat a nullable expression as non-nullable if you're certain it isn't null. is null, and it is safe to assign it to a non-nullable variable i.e.
Null-aware operators are used in almost every programming language to check whether the given variable value is Null. The keyword for Null in the programming language Dart is null. Null means a variable which has no values assign ever and the variable is initialized with nothing like.
Try adding a null check ('!') as compiler suggests
class Class1 {
final Function? onPressed;
const Class1({this.onPressed});
callMethod() {
if (onPressed != null) {
onPressed!(); //Note: ! is added here
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With