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) {});
2
  • could you explain a little more why use Function keyword, please
    – ROB
    Commented Nov 18, 2020 at 1:46
  • 1
    @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).
    – Blasanka
    Commented Nov 18, 2020 at 2:59
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
  • 1
    I like this example :)
    – Ayrix
    Commented Dec 12, 2022 at 23:04
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.

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.