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

Share Improve this question asked Mar 24 at 16:48 Wouter VandenputteWouter Vandenputte 2,1135 gold badges32 silver badges55 bronze badges 4
  • most likely you need final objType = T; and not final objType = T.runtimeType; – pskink Commented Mar 24 at 17:08
  • That indeed worked! If you add it as an answer I will accept it :D – Wouter Vandenputte Commented Mar 24 at 18:01
  • I bet that'll still cause havoc when your code gets symbols mangled in a release version. – Randal Schwartz Commented Mar 24 at 20:50
  • It's worth noting that the hashCode 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
Add a comment  | 

1 Answer 1

Reset to default 0

I 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