简体   繁体   中英

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

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;

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.

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.

Callbacks can accept parameters. In your case update it to;

final VoidCallback(double height)? callback;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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