Ivan
Ivan

Reputation: 1526

Default value for parameter of Function type in Dart

Consider a function in Dart file

void myFunction({int input = 1, Function(int, String) callback}) {
// ...
}

So, I wonder is it possible at all to specify a default value for the callback parameter, for instance it can be something like (_, _) => { }.

P.S. I know it has null as default value and ?? can help to avoid NPE, I'm just curious is it possible at all. Cheers.

Upvotes: 15

Views: 16540

Answers (2)

farouk osama
farouk osama

Reputation: 2519

The default value of an optional parameter must be constant.

This is what the documents said

This thing can be bypassed like this:

 dynamic myCallback(int a,String b) {
      
  }
  
 void myFunction({int input = 1, Function(int, String) callback }) {
    if (callback == null) callback = myCallback;
  }

Edit:

Alternatively, you can use anonymous function with out myCallback function like this:

void myFunction({int input = 1, Function(int, String) callback }) {
   if (callback == null) callback = (a,b){};
  }

Upvotes: 4

Mobina
Mobina

Reputation: 7109

You can do something like:

dynamic func(int i, String s) {
  print(i.toString() + s);
}

void myFunction({int input = 1, Function(int, String) callback = func}) {
  callback(input, " .");
}

void main() {
  myFunction(input: 2);
}

Upvotes: 14

Related Questions