Skip to content

Instantly share code, notes, and snippets.

@letsar
Last active November 13, 2020 02:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save letsar/19fbfe2872d4464785b3ea1e1af221f1 to your computer and use it in GitHub Desktop.
Save letsar/19fbfe2872d4464785b3ea1e1af221f1 to your computer and use it in GitHub Desktop.
A ChangeNotifier implementation using List
typedef VoidCallback = void Function();
class _Listener {
_Listener(this.func);
final VoidCallback func;
VoidCallback afterNotify;
void call() {
if (afterNotify == null) {
func();
}
}
}
class ChangeNotifier {
List<_Listener> _listeners = List<_Listener>();
int _notifications = 0;
bool get _notifying => _notifications > 0;
bool get hasListeners {
return _listeners.isNotEmpty;
}
void addListener(VoidCallback listener) {
_listeners.add(_Listener(listener));
}
void removeListener(VoidCallback listener) {
for (int i = 0; i < _listeners.length; i++) {
if (_listeners[i].func == listener) {
if (_notifying) {
_listeners[i].afterNotify = () => _listeners.removeAt(i);
} else {
_listeners.removeAt(i);
}
break;
}
}
}
void dispose() {
_listeners = null;
}
void notifyListeners() {
_notifications++;
if (_listeners.isEmpty) {
_notifications--;
return;
}
if (_listeners != null) {
final int end = _listeners.length;
for (int i = 0; i < end; i++) {
try {
_listeners[i]();
} catch (exception, stack) {
print('error');
}
}
for (int i = end - 1; i >= 0; i--) {
_listeners[i].afterNotify?.call();
}
}
_notifications--;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment