我有一个带有onTap参数的方法
myFunc({onTap}){
return onTap;
}
然后,我需要像这样使用它myFunc(
onTap: print('lorem ipsum');
)
我怎样才能做正确?谢谢
Function
(您可以使用ValueChange, Voidcallback)。myFunc({Function onTap}){
onTap();
}
//invoke
myFunc(onTap: () {});
如果你想传递参数:
myFunc({Function onTap}){
onTap("hello");
}
//invoke
myFunc(onTap: (String text) {});
更详尽的使用方式可以是:
void main() {
callbackDemo(onCancel: () {
print("Cancelled");
}, onResend: () {
print("Resend");
}, onSuccess: (otp) {
print(otp);
});
}
void callbackDemo({required onSuccess(String otp),
onCancel, onResend}) {
onCancel();
onResend();
onSuccess("123456");
}
之前的解决方案采用了命名参数,使问题变得复杂。这里是最简单的函数,它接受回调函数而没有任何额外的复杂性:
testFunction(Function func){
func();
}
void main() {
testFunction( () {
print('function being called');
});
}
testFunction()
被定义为接受一个没有参数的函数(因此数据类型为 Function
)。当我们调用该函数时,我们传递一个匿名函数作为参数。
T
的参数和一个类型为 int
的参数。 void forEach(Function(T, int) cb){
Node<T>? current = head;
int index = 0;
while (current != null){
cb(current.value, index);
index++;
current = current.next;
}
}
调用它:
list.forEach((v, i){
print(v);
});
String
)。 - Blasanka