skip to Main Content

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


  1. It happens because T is already is type by itself. When you call runtimeType from Type you get a Type;

    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:

    extension Wrapper on Map<String, dynamic> {
      T? property<T>({required String key}) {
        final value = this[key];
    
        if (T.toString() == value.runtimeType.toString()) {
          return value as T;
        }
        return null;
      }
    }
    

    Then call it with your type with every property:

    map.property<int>(key: 'intKey');
    map.property<String>(key: 'someString');
    

    Next case works fine:

    Map<String, dynamic> map = {'str': 'Some string', 'int': 42, 'array': []};
    
    assert(map.property<int>(key: 'int') == 42); // true
    
    Login or Signup to reply.
  2. T is already a Type object, so you can just compare it directly:

    T == value.runtimeType
    

    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 of T, then you instead should use simply:

    value is T
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search