Skip to content

Null-safety: null check not working with type Function #1828

Closed
@esotericpig

Description

@esotericpig

I couldn't find an issue about this, but maybe it has already been mentioned.

The below code doesn't compile:

class Tester {
  void Function()? myFunc;
  
  Tester(this.myFunc);
  
  void test() {
    if(myFunc != null) {
      // ERROR: The function can't be unconditionally invoked because it can be 'null'.
      myFunc();
    }
  }
}

The workaround of course:

myFunc!();

It seems like the null-check if-statement should resolve it, just like when using a variable of any other type, but it doesn't work with type Function, but works with other types:

class Tester2 {
  String? name;
  
  void test() {
    if(name != null) {
      // Compiles fine.
      print(name);
    }
  }
}

Thanks

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions