简体   繁体   English

如何在 dart flutter 中创建回调函数?

[英]How to create callback function in dart flutter?

I have this method with onTap parameter我有这个带有 onTap 参数的方法

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 )请注意,您可以指定参数或避免,并且我添加了Function (您可以使用ValueChangeVoidcallback

myFunc({Function onTap}){
   onTap();
}

//invoke
myFunc(onTap: () {});

If you want to pass arguments:如果要传递参数:

myFunc({Function onTap}){
   onTap("hello");
}

//invoke
myFunc(onTap: (String text) {});

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. testFunction()被定义为接受一个没有参数的函数(因此是Function的数据类型。当我们调用该函数时,我们传递一个匿名函数作为参数。

Here is an example that adds type safety to the parameters of the callback:这是一个为回调的参数添加类型安全的示例:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM