/// Subscribe to a keyboard event.
/// [listener] object to listen the event.
/// Returns a subscribing id that can be used to unsubscribe.
int add({required KeyboardListener listener}) {
final int length = _listenersKeyboardEvents.length;
_listenersKeyboardEvents[length] = listener;
return length;
}
If you add one listener listener1 (length is 0, becomes 1):
{0: listener1}
Then add a second listener listener2 (length is 1, becomes 2):
{0: listener1, 1: listener2}
Then remove the one with id 0 (length is 2, becomes 1):
{1: listener2}
But now if you add a third listener listener3, since length is now 1, it will overwrite listener2, and you'd get:
{1: listener3}
The solution is creating an independent counter that never repeats:
static int _count = 0;
/// Subscribe to a keyboard event.
/// [listener] object to listen the event.
/// Returns a subscribing id that can be used to unsubscribe.
int add({required KeyboardListener listener}) {
_listenersKeyboardEvents[_count] = listener;
_count++;
return _count;
}
There is a bug here:
If you add one listener
listener1
(length is 0, becomes 1):{0: listener1}
Then add a second listener
listener2
(length is 1, becomes 2):{0: listener1, 1: listener2}
Then remove the one with id 0 (length is 2, becomes 1):
{1: listener2}
But now if you add a third listener
listener3
, since length is now 1, it will overwritelistener2
, and you'd get:{1: listener3}
The solution is creating an independent counter that never repeats: