5

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.

Axel
  • 4,365
  • 11
  • 63
  • 122

1 Answers1

10

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
    }
  }
}
Pavel Shastov
  • 2,657
  • 1
  • 18
  • 26