Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart null safety complains about a function becoming null despite the null check being there [duplicate]

Tags:

flutter

dart

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.

like image 510
Damon Avatar asked Mar 07 '21 08:03

Damon


People also ask

How do you handle null safety in darts?

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.

How do you check for null in darts?

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.


1 Answers

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
    }
  }
}
like image 127
Pavel Shastov Avatar answered Oct 07 '22 12:10

Pavel Shastov