[英]How to declare type of anonymous functions in Dart?
Say I need a function passed into a method which takes a String and turns it into a double:假设我需要一个 function 传递给一个方法,该方法接受一个字符串并将其转换为双精度:
void strToDouble(String input, Function converter) {
print('As a double, $input is ${converter(input)}`);
}
(Obviously toy example) (显然是玩具示例)
How can I declare the type of converter
as a function that turns a String
to double?如何将converter
的类型声明为 function 将String
变为双倍?
To declare your converter
callback as a Function
that takes a String
and returns a double
, its type should be: double Function(String)
.要将您的converter
回调声明为接受String
并返回double
的Function
,其类型应为: double Function(String)
。 Therefore your strToDouble
function would be:因此,您的strToDouble
function 将是:
void strToDouble(String input, double Function(String) converter) {
...
}
You can use typedef
你可以使用typedef
typedef double ConvertStringToDouble(String input);
void main() {
ConvertStringToDouble cs = (String input){
return double.parse(input);
};
strToDouble("29.0", cs);
}
void strToDouble(String input, ConvertStringToDouble converter) {
print("As a double, $input is ${converter(input)}");
}
This is the function you want to call to get the output as double by passing the string and the converter function:这是您要调用的 function 以通过传递字符串和转换器 function 将 output 作为双倍:
dynamic dynamicConverter (String input, double Function(dynamic input) convert){
return convert.call(input);
}
You will have to use it like below:您必须像下面这样使用它:
double output = dynamicConverter("120", (input) {
return double.parse(input);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.