In Dart/Flutter I need that a closure / arrow function passed to a class instance would be able to use a variable of that class instance. Is there a way?
For example, I have a widget that will have a context in build method, as usual. I need to pass a closure to the widget and the closure needs to use that context.
CodePudding user response:
If the class is yours then you can do
class MyWidget extends StatelessWidget {
final void Function(BuildContext) closure;
const MyWidget({required this.closure, Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
closure(context);
return ...
}
}
void closure(BuildContext context) {
// called from MyWidget, context is also from there.
}
// pass function to class
const MyWidget(closure: closure);