15

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

4 Answers 4

27

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) {});
Sign up to request clarification or add additional context in comments.

2 Comments

could you explain a little more why use Function keyword, please
@ROB Its a type in dart for function. Indicating that the parameter is type of function. You must pass a argument type of function(Just like other variable types. Ex: String).
9

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");
}

1 Comment

I like this example :)
5

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.

Comments

1

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);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.