简体   繁体   English

如何在 FLUTTER 中的 RaisedButton.onpressed 中传递对 function 的引用,但带有参数?

[英]How to pass a reference to a function in RaisedButton.onpressed in FLUTTER, but with parameters?

I already understood that we should call functions in FLUTTER without parentheses because you want to establish a reference to that function, not execute it.我已经明白我们应该在不带括号的情况下调用 FLUTTER 中的函数,因为您想建立对 function 的引用,而不是执行它。

But what if you want to pass parameters to that function?但是如果你想给那个 function 传递参数怎么办? How can I tell FLUTTER that I want to reference the function (not execute it), but pass arguments to it?我如何告诉 FLUTTER 我想引用 function(不执行它),但将 arguments 传递给它? The arguments are usually specified inside parentheses. arguments 通常在括号内指定。

I tried calling a function with parentheses when I have parameters to indicate, and it seems to work perfectly.当我有参数要指示时,我尝试用括号调用 function,它似乎工作得很好。 It only executes the function when the button is pressed.... I'm a little confused.它只在按下按钮时执行 function ....我有点困惑。

If the parameters line up you can pass a reference to the function and it will be called with those parameters.如果参数对齐,您可以传递对 function 的引用,它将使用这些参数进行调用。

String validate(String? value) {
  if (value == null) {
    return 'Required';
  }
  return null;
}

TextFormField(
  // Signature of validator and validate are the same
  validator: validate
)

If the signatures don't overlap you have to use an anonymous function.如果签名不重叠,您必须使用匿名 function。

TextFormField(
  validator: (value) => someOtherFunction(),
)

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

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