Currently I have LOTS of this in a class (a ChangeNotifier
so pretty much one for each field):
String _name;
String get name => _name;
set name(String value) {
if (_name == value) {
return;
}
_name = value;
notifyListeners();
}
In C# I had the same problem with INotifyPropertyChanged
, but there we can pass variables by reference, so it's easier to make a function for encapsulating this kind of behavior, and many libraries actually supply them.
I came up with this, but I am not sure if there are better (simpler) alternatives:
typedef ValueSetter<T> = void Function(T); // or imported from [ChangeNotifier]
...
String _name;
String get name => _name;
set name(String value) => _setAndNotifyIfNotEqual(_name, value, (v) => _name = v);
/// If [newValue] is different than [oldValue], call [setter] with [newValue],
/// then call [notifyListeners].
void _setAndNotifyIfNotEqual<T>(T oldValue, T newValue, ValueSetter setter) {
if (newValue != oldValue) {
setter(newValue);
notifyListeners();
}
}
Are there any better ways of achieving this in Dart?