We are dealing with a legacy API where the API in some cases will return a different type than expected. So I want to have some extion on a map to retrieve the property or return null.
extension Wrapper<T> on Map<String, dynamic> {
T? property({required String key}) {
final value = this[key];
if (T.runtimeType == value.runtimeType) {
return value;
}
return null;
}
}
Using the method:
final String? val2 = map.property(key: "bool");
The problem is that the T.runtimeType gives _Type instead of String.
How can I get the real property type?
2
Answers
It happens because T is already is type by itself. When you call
runtimeType
fromType
you get aType
;Try use
toString()
method from Type and compare the value.For your case i did couple changes.
Move generic from
Wrapper<T>
to method property:Then call it with your type with every property:
Next case works fine:
T
is already aType
object, so you can just compare it directly:Note that such an equality check tests for exact type identity; it will not return true if one type is a subtype of the other.
If you want to check if
value.runtimeType
is a subtype ofT
, then you instead should use simply: