[英]Default value for parameter of Function type in Dart
Consider a function in Dart file考虑 Dart 文件中的 function
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 (_, _) => { }
.所以,我想知道是否有可能为
callback
参数指定一个默认值,例如它可以是(_, _) => { }
之类的东西。
PS I know it has null
as default value and ??
PS我知道它有
null
作为默认值和??
can help to avoid NPE
, I'm just curious is it possible at all.可以帮助避免
NPE
,我只是好奇这是否可能。 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:或者,您可以使用不带myCallback 函数
myCallback
匿名函数,如下所示:
void myFunction({int input = 1, Function(int, String) callback }) {
if (callback == null) callback = (a,b){};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.