简体   繁体   English

Dart:如何将function作为参数传递

[英]Dart: How to pass function as parameter

Id like to call a function from another function, this is my code:我想从另一个 function 呼叫一个 function,这是我的代码:

  void fooA () {
    //do something
  }
  
  void fooB (fooC) {
    fooC();
  }
  
  fooB (fooA);

Why is fooA not executed?为什么 fooA 没有被执行?

The code you provided functions:您提供的代码功能:

void fooA () {
  print('hi');
}

void fooB (fooC) {
  fooC();
}

main() {
  fooB (fooA);
}

Output: Output:

hi

However, it is better to fully type function arguments, as in:但是,最好完整键入 function arguments,如:

void fooA() {
  print('hi');
}

void fooB(void Function() fooC) {
  fooC();
}

main() {
  fooB(fooA);
}

Note the fully descriptive type declaration void Function() fooC .请注意完整的描述性类型声明void Function() fooC Doing so enables the compiler to use static type checking to ensure the passed in function has the correct parameter and return types.这样做使编译器能够使用 static 类型检查来确保传入的 function 具有正确的参数和返回类型。

References参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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