我知道Function类可以作为参数传递给另一个函数,如下所示:

void doSomething(Function f) {
    f(123);
}

但是有没有办法约束参数和函数参数的返回类型呢?

例如,在本例中,f直接被一个整数调用,但如果它是一个接受不同类型的函数呢?

我try 将其作为Function<Integer>传递,但函数不是参数类型.

有没有其他方法可以指定作为参数传递的函数的签名?

推荐答案

DART V1.23添加了用于编写函数类型的新语法,该语法也可以内联工作.

void doSomething(Function(int) f) {
  f(123);
}

与函数参数语法相比,它的优势在于,您还可以将其用于变量或任何您想要编写类型的地方.

void doSomething(Function(int) f) {
  Function(int) g = f;
  g(123);
}

var x = <int Function(int)>[];

int Function(int) returnsAFunction() => (int x) => x + 1;
    
int Function(int) Function() functionValue = returnsAFunction;

Dart相关问答推荐

DART列表由以奇怪方式链接的列表(即二维数组)组成

使用arm64v8/DART Docker映像进行编译时不支持DART镜像

Dart 列表中的 addAll() 和 followBy() 有什么区别?

Task 'app:processDebugResources'的Flutter执行失败

从 Future 实例中获取值

Flutter:如何同步使用 SharedPreferences?

Flatter有数据绑定吗?

Flutter插件和Flutter模块之间有什么区别?

如何仅从 DateTime.now() 中提取时间;

如何判断 Dart NNBD 中的泛型类型是否可以为空?

什么时候在 Dart 中使用 num

Error: The argument type "String?"can't be assigned to the parameter type"String" because "String?"s nullable and "String"isn't

多次打印同一个字符而不循环

Dart 中 await for 和 listen 的区别

Dart 的服务器端框架

在 Dart 中创建具有可变数量的参数或参数的函数

Dart 中的 List.shuffle()?

dart 折叠(Fold)与减少(Reduce)

何时在 Dart 中使用 part/part of 与 import/export?

在 Dart 中为数字添加前导零