I have a widget (slider) that changes a value.
Right now, I am passing a VoidCallback to each slider, so they can update the individual setter of the provider.
Is it possible to pass the setter in the constructor of the slider, so it can call the setter directly, thus simplifying the construction of the slider (no VoidCallbacks needed)?
CodePudding user response:
You can by wrapping the setter in a function. So a callback is still needed but it's a lean wrapper around the setter. Not much boilerplate to handle here. I made an example on gist/dartpad:
https://dartpad.dev/?id=38f013e47f8c85057c44a0a326df33dd
void main() async {
final a = A(value: 2);
print('A=${a.value}');
final setter = (int i) => a.data = i;
final b = B(callback: setter);
b.exec(10);
print('A=${a.value}');
}
class A {
int value;
A({required this.value});
set data(int newValue) => value = newValue;
}
class B {
final void Function(int) callback;
B({required this.callback});
void exec(int i){
callback(i);
}
}