I have an abstract class that adds strings to a list and does some other stuff.
abstract class Abc {
final _list = <String>[];
Function(String) addedValue;
void add(String s) {
_list.add(s);
if (this.addedValue != null) this.addedValue(s);
}
}
In my subclass I want a callback every time a string is added to the list. There are also other subclasses that may or may not want callbacks.
class Xyz extends Abc {
String _data = '';
Xyz() {
this.addedValue = _added;
}
void _added(String s) {
_data += '$s,';
print('data: $_data');
}
}
main() {
var a = Xyz();
a.add('hello');
a.add('goodbye');
a.addedValue('a'); // Prefer if this was not possible.
a.addedValue = null; // Prefer if this was not possible.
}
What is the cleanest way to provide the superclass with the callback method?
- I can't pass it in a constructor because it is an instance method.
- I can't make it static because it needs access to the instance.
- I would prefer not to expose the callback methods/setters beyond the subclass.
- The superclass and subclass will not be in the same library.