void main(List<String> args) {
  noParametersFunc();
  withParametersFunc("wyl");
  test();
}

//无参数函数
void noParametersFunc() {
  print("No parameters function");
}

//带参数函数
void withParametersFunc(String name) {
  print("Hello, $name!");
}

匿名函数

Function test = () {
  print("abcd");
};// <-- 必须要有这个;

其中的 ↓ 就是匿名函数

() {
  print("abcd");
};

这个匿名函数赋值给Function类型的test变量

当匿名函数里面只有一行的时候,可以在简写成:

() => print();

() => {print()}; 
// => 后面只能跟一个表达式(Expression),不能跟语句块(Statement)
// {} 被视为返回 void 的表达式

调用

test();

回调函数

无参

Function test = () => print("abcd2");
//回调函数 ,通过传入一个Function
void testFuncCallback(Function callback) {
  //业务逻辑执行结束
  callback(); //执行回调
}
//调用
testFuncCallback(test);

有参

Function test = (String name) => print("abcd2 $name");
//回调函数 ,通过传入一个Function
void testFuncCallback(Function func) {
  //业务处理
  String name = "wyl";
  func(name);
}
//调用
testFuncCallback(test);
testFuncCallback((String name) {
    print("Anonymous function: $name");
});

关于Function

Function是一个函数类型,也就是说所有的函数都是这个类型。有点类似c语言中的函数指针,指向一个函数,然后这个指针可以直接调用。

比如:

void hello()
{
	print('hello')
}
Function func = hello;
func();//直接调用
//有参也是同理
int a=10,b=20;
func(a,b);

但是:func可以传入任何函数(参数个数、类型任意),类型不安全。这种方式编译时不会报错,但是运行时会崩溃。不建议使用