castMapValues method

Map? castMapValues(
  1. Map map,
  2. TypeInfo typeInfo, {
  3. bool nullable = false,
})

Cast map values to reflectedType if type == reflectedType or return null.

  • If nullable is true casts to a Map of nullable values.

Implementation

Map? castMapValues(Map map, TypeInfo typeInfo, {bool nullable = false}) {
  if (!typeInfo.isMap) {
    return map;
  }

  var keyType = typeInfo.argumentType(0) ?? TypeInfo.tDynamic;
  var valueType = typeInfo.argumentType(1) ?? TypeInfo.tDynamic;

  if (valueType.type == reflectedType) {
    Map? callKey<K>() => map is Map<K, O>
        ? map
        : map.map<K, O>((key, value) => MapEntry<K, O>(key, value));
    Map? callKeyNullable<K>() => map is Map<K, O?>
        ? map
        : map.map<K, O?>((key, value) => MapEntry<K, O?>(key, value));

    var m = nullable
        ? keyType.callCasted(callKeyNullable)
        : keyType.callCasted(callKey);

    return m;
  } else {
    Map? callKey<K>() => valueType.callCasted(<V>() {
          return map is Map<K, V>
              ? map
              : map.map<K, V>((key, value) => MapEntry<K, V>(key, value));
        });

    Map? callKeyNullable<K>() => valueType.callCasted(<V>() {
          return map is Map<K, V?>
              ? map
              : map.map<K, V?>((key, value) => MapEntry<K, V?>(key, value));
        });

    var m = nullable
        ? keyType.callCasted(callKeyNullable)
        : keyType.callCasted(callKey);
    return m;
  }
}