Ashtav
Ashtav

Reputation: 2966

How to create callback function in dart flutter?

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

Upvotes: 15

Views: 35650

Answers (4)

Jose Miralles
Jose Miralles

Reputation: 542

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

Upvotes: 1

Minion
Minion

Reputation: 1064

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

Upvotes: 9

Mark Tyers
Mark Tyers

Reputation: 3239

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.

Upvotes: 5

Blasanka
Blasanka

Reputation: 22417

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

Upvotes: 27

Related Questions