如何在Dart Flutter中创建回调函数?

14

我有一个带有onTap参数的方法

myFunc({onTap}){
   return onTap;
}
然后,我需要像这样使用它
myFunc(
   onTap: print('lorem ipsum');
)

我怎样才能做正确?谢谢

4个回答

23
你可以按照以下方式进行操作。请注意,您可以指定参数或避免指定参数,我已添加了Function(您可以使用ValueChange, Voidcallback)。
myFunc({Function onTap}){
   onTap();
}

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

如果你想传递参数:

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

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

你能否再解释一下为什么要使用Function关键字? - ROB
1
@ROB 这是 Dart 中的一种函数类型。它表示参数是函数类型。您必须传递一个函数类型的参数(就像其他变量类型一样。例如:String)。 - Blasanka

6

更详尽的使用方式可以是:

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
我喜欢这个例子 :) - Ayrix

3

之前的解决方案采用了命名参数,使问题变得复杂。这里是最简单的函数,它接受回调函数而没有任何额外的复杂性:

testFunction(Function func){
    func();
}

void main() {
    testFunction( () {
        print('function being called');
    });
}

testFunction() 被定义为接受一个没有参数的函数(因此数据类型为 Function)。当我们调用该函数时,我们传递一个匿名函数作为参数。


1
这是一个为回调函数参数添加类型安全的示例:
回调函数接受一个类型为 T 的参数和一个类型为 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;
    }
  }

调用它:

list.forEach((v, i){
    print(v);
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接