简体   繁体   中英

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 (_, _) => { } .

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

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);
}

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 anonymos functaion with out myCallback funcation like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM