简体   繁体   English

Dart 中 Function 类型的参数默认值

[英]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.

相关问题 Dart 为参数设置默认值 - Dart set default value for parameter Flutter ,dart,参数 'colour' 因为它的类型不能有 'null' 的值,但是隐含的默认值是 'null' - Flutter ,dart,The parameter 'colour' can't have a value of 'null' because of its type, but the implicit default value is 'null' function 作为参数,在 dart 中具有泛型 object 返回类型 - function as parameter with generic object return type in dart 如何在 dart 中将默认参数分配给除 map 参数之外的函数 - How to assign a default parameter to a function aside of map parameter in dart Dart:使用非常量值作为默认构造函数参数 - Dart: Use non-constant value as default constructor parameter 参数“answerQuestion”的值不能为“null”,因为它的类型为“Function”,但隐含的默认值为“null” - The parameter 'answerQuestion' can't have a value of 'null' because of its type 'Function', but the implicit default value is 'null' 由于其类型为 Dart,该参数的值不能为“null” - The parameter can't have a value of 'null' because of its type in Dart 如何在 dart 中调用采用 Map 类型参数的 function? - How to call a function which takes parameter of type Map in dart? 参数不能具有 null 的值,因为它的类型为 Flutter Dart - Parameter cant have value of null because of its type Flutter Dart Dart Flutter:为类构造函数设置默认值时,可选参数的默认值必须是常量 - Dart Flutter: The default value of an optional parameter must be constant when setting a default value to class constructor
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM