I have a function lets say:
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;
CodePudding user response:
You can set up your callback function like this:
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.
CodePudding user response:
Callbacks can accept parameters. In your case update it to;
final VoidCallback(double height)? callback;
CodePudding user response:
Dart is a statically-scoped language. That means that the scope for functions is determined at compilation-time from where the function is defined in the code. A function can access variables only in its own scope or in the parent scopes of its definition.
The caller of a function therefore cannot directly inject a variable into the callee. It instead could modify an existing variable declared in an ancestor scope shared with the callee. 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).
As others have noted, the proper approach to take instead is to parameterize your callback by making the caller supply it with an argument.