Last active
January 23, 2021 12:16
-
-
Save letsar/2b782086d5090cc070d7743b79a28357 to your computer and use it in GitHub Desktop.
ChangeNotifier with List and queuing
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 ChangeNotifier { | |
List<VoidCallback> _listeners = List<VoidCallback>(); | |
List<int> _toRemove = List<int>(); | |
bool _notifying = false; | |
bool get hasListeners { | |
return _listeners.isNotEmpty; | |
} | |
void addListener(VoidCallback listener) { | |
_listeners.add(listener); | |
} | |
void removeListener(VoidCallback listener) { | |
for (int i = 0; i < _listeners.length; i++) { | |
if (_listeners[i] == listener) { | |
if (_notifying) { | |
_toRemove.add(i); | |
} else { | |
_listeners.removeAt(i); | |
} | |
break; | |
} | |
} | |
} | |
void dispose() { | |
_listeners = null; | |
} | |
void notifyListeners() { | |
_notifying = true; | |
if (_listeners != null) { | |
final int start = _listeners.length - 1; | |
for (int i = start; i >= 0; i--) { | |
try { | |
_listeners[i](); | |
} catch (exception, stack) { | |
print('error'); | |
} | |
} | |
for (int i = _toRemove.length - 1; i >= 0; i--) { | |
_listeners.removeAt(_toRemove[i]); | |
} | |
_toRemove.clear(); | |
} | |
_notifying = false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment