简体   繁体   English

dart / flutter中的回调function可以注入变量吗?

[英]Can a variable be injected into a callback function in dart / flutter?

I have a function lets say:我有一个 function 让我们说:

class MyDelegate {
  MyDelegate({this.callback});
  final VoidCallback? callback;

@override Size layout(){


  var _height = 10;

  debugPrint('height: '+ _height.toString());
  callback!();

  return _height

}

}

Now I have a callback that I want to run:现在我有一个我想运行的回调:

()
{
var _modifiedHeight;
debugPrint('My modified height is: '+ _modifiedHeight.toString());
}

I was hoping to have _modifiedHeight which is supplied as part of the callback derive its value from _height , in this case I would like it to be _modifiedHeight = _height + 50;我希望有_modifiedHeight作为回调的一部分提供从_height派生它的值,在这种情况下我希望它是_modifiedHeight = _height + 50;

You can set up your callback function like this:您可以像这样设置回调 function:

class MyDelegate {
  MyDelegate({this.callback});
  final Function(double)? callback;
  @override Size layout(){

  var _height = 10;

  debugPrint('height: '+ _height.toString());
  callback!(_height)

  return _height

 }
}

(double height){
   var _modifiedHeight;
   debugPrint('My modified height is: '+ (height + 50).toString());
 }

FYI a VoidCallback is a Function and I guess I just have a preference for using Function.仅供参考, VoidCallback 是 Function ,我想我只是更喜欢使用 Function。

Dart is a statically-scoped language. Dart 是一种静态范围的语言。 That means that the scope for functions is determined at compilation-time from where the function is defined in the code.这意味着函数的 scope 是在编译时从代码中定义 function 的地方确定的。 A function can access variables only in its own scope or in the parent scopes of its definition. function 只能在其自己的 scope 或其定义的父范围内访问变量。

The caller of a function therefore cannot directly inject a variable into the callee.因此 function 的调用者不能直接向被调用者注入变量。 It instead could modify an existing variable declared in an ancestor scope shared with the callee.相反,它可以修改在与被调用者共享的祖先 scope 中声明的现有变量。 However, in the case of callbacks where the caller can't control where the callback was defined, that essentially means the global scope (or static class variables).但是,在调用者无法控制回调定义位置的回调的情况下,这实际上意味着全局 scope(或static class 变量)。

As others have noted, the proper approach to take instead is to parameterize your callback by making the caller supply it with an argument.正如其他人指出的那样,正确的方法是通过让调用者为其提供参数来参数化回调。

Callbacks can accept parameters.回调可以接受参数。 In your case update it to;在您的情况下将其更新为;

final VoidCallback(double height)? callback;

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

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