admin管理员组文章数量:1399925
I have the following map that associates a Type with a list of methods to be executed at some point where the argument is the required type.
final Map<Type, List<Function>> _listeners = {};
void registerListener<T>(void Function(T) listener) {
final objType = T.runtimeType;
_listeners[objType] ??= [];
_listeners[objType]!.add(listener);
}
The problem however is that this does not work...
yet the lists are present in the Map
though.
registerListener((MyObject x) => {});
final test = _listeners[MyObject];
print(test);
final test2 = _listeners[MyObject().runtimeType];
print(test2);
both logs print null
instead of a list of functions. Yet the list is stored with the method present in it as we can see from this debugger statement
I have the following map that associates a Type with a list of methods to be executed at some point where the argument is the required type.
final Map<Type, List<Function>> _listeners = {};
void registerListener<T>(void Function(T) listener) {
final objType = T.runtimeType;
_listeners[objType] ??= [];
_listeners[objType]!.add(listener);
}
The problem however is that this does not work...
yet the lists are present in the Map
though.
registerListener((MyObject x) => {});
final test = _listeners[MyObject];
print(test);
final test2 = _listeners[MyObject().runtimeType];
print(test2);
both logs print null
instead of a list of functions. Yet the list is stored with the method present in it as we can see from this debugger statement
1 Answer
Reset to default 0I believe you may add one more parameters for object initiation, because T it's an abstraction meanwhile T.runtimeType
it will display Type
void registerListener<T>(T key, void Function(T data) listener) {
final objType = key.runtimeType;
print('RUNTIME: $objType');
print('RUNTIME: ${T.runtimeType}');
_listeners[objType] ??= [];
_listeners[objType]!.add(listener);
}
本文标签: FlutterDart Map with Type as keyStack Overflow
版权声明:本文标题:FlutterDart Map with Type as key - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744239358a2596712.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
final objType = T;
and notfinal objType = T.runtimeType;
– pskink Commented Mar 24 at 17:08hashCode
of a type isn't guaranteed to be the same value between app runs, app updates, or between instances of the app on different platforms. It should be fine for a map that only lives for the duration of the app, but you shouldn't depend on this for persisted data. – Abion47 Commented Mar 25 at 21:32