2

Is there an easy way to invoke the function with null check ?

Function(String) onTextReady;

Is there an easy way to safely invoke this function. In Kotlin for example I would use invoke:

onTextReady?.invoke('Hello world');

I tried onTextReady?.('Hello world'); but Dart doesn't support this.

vovahost
  • 34,185
  • 17
  • 113
  • 116

1 Answers1

2

Well, short answer, no (with the operator). The null-aware ?. operator in Dart will work only with object call to members, not to null-check a function execution directly.

In this case bellow, it would work:

class MyClass {
  Function(String s) onTextReady = (s) => print(s);
}

main() {
  var nullObject;
  nullObject?.onTextReady('null'); // do nothing

  var notNull = MyClass();
  notNull?.onTextReady('not null'); // print 'not null'
}

You would need to check it manually (!= null) to be null-safe:

main() {
  Function(String) onTextReady;

  if(onTextReady != null) {
    onTextReady('null');
  }

  Function(String) onTextReady2 = (s) => print(s);

  if(onTextReady2 != null) {
    onTextReady2('not null');
  }
}
  • 2
    I appreciate the example but usually `clazz` is used to name variables which hold a reference to the class, in your case you are using it to name an object which is confusing. – vovahost Jun 16 '19 at 04:55
  • This answer worked awesome for me : https://stackoverflow.com/a/61141239/6665568 – Natesh bhat Apr 10 '20 at 13:29