Skip to content

Instantly share code, notes, and snippets.

@lesnitsky
Created September 30, 2021 12:51
Show Gist options
  • Save lesnitsky/1e30966c49603513e75c528cc71d05cf to your computer and use it in GitHub Desktop.
Save lesnitsky/1e30966c49603513e75c528cc71d05cf to your computer and use it in GitHub Desktop.
runtimeType key
class Storage<T> {
final _internal = <Type, T>{};
void add(T value, [Type? type]) {
_internal[type ?? T] = value;
}
T get<T>() {
return _internal[T] as T;
}
}
class Boxed<T> {}
class Container {
final storage = Storage<Boxed>();
add(Boxed value) {
storage.add(value, value.runtimeType);
// ^^^^^^^^^^^^^^^^^^
// can't use generic
}
Boxed<T> get<T>() {
return storage.get<Boxed<T>>();
}
}
final container = Container();
void main() {
final intValue = Boxed<int>();
final stringValue = Boxed<String>();
final doubleValue = Boxed<double>();
final items = [intValue, stringValue, doubleValue];
items.forEach((element) {
container.add(element);
});
assert(container.get<int>() == intValue);
assert(container.get<String>() == stringValue);
assert(container.get<double>() == doubleValue);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment