I have this method with onTap parameter
myFunc({onTap}){
return onTap;
}
then, I need to use it like this
myFunc(
onTap: print('lorem ipsum');
)
How I can make it correctly? thanks
You can do like below. Note that you can specify parameter or avoid and I have added Function(You can use ValueChange, Voidcallback)
myFunc({Function onTap}){
onTap();
}
//invoke
myFunc(onTap: () {});
If you want to pass arguments:
myFunc({Function onTap}){
onTap("hello");
}
//invoke
myFunc(onTap: (String text) {});
A more exhaustive usage could be like
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");
}
The previous solution complicates matters by using named parameters. Here is the simplest possible function that takes a callback function without any of the extra complexity:
testFunction(Function func){
func();
}
void main() {
testFunction( () {
print('function being called');
});
}
The testFunction() is defined as taking a function with no arguments (hence the data type of Function. When we call the function we pass an anonymous function as an argument.
Here is an example that adds type safety to the parameters of the callback:
The callback takes in a parameter of type T, and another parameter of type 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;
}
}
Calling it:
list.forEach((v, i){
print(v);
});