Last active
November 13, 2020 02:29
-
-
Save letsar/19fbfe2872d4464785b3ea1e1af221f1 to your computer and use it in GitHub Desktop.
A ChangeNotifier implementation using List
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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