parseMap<K, V> static method

Map<K, V>? parseMap<K, V>(
  1. Object? value, {
  2. Map<K, V>? def,
  3. TypeElementParser<K>? keyParser,
  4. TypeElementParser<V>? valueParser,
})

Tries to parse a Map.

  • Returns def if value is null or an empty String.

Implementation

static Map<K, V>? parseMap<K, V>(Object? value,
    {Map<K, V>? def,
    TypeElementParser<K>? keyParser,
    TypeElementParser<V>? valueParser}) {
  if (value == null) return def;

  if (value is Map<K, V>) {
    return value;
  }

  keyParser ??= parserFor<K>() as TypeElementParser<K>?;
  keyParser ??= (k) => k as K;

  valueParser ??= parserFor<V>() as TypeElementParser<V>?;
  valueParser ??= (v) => v as V;

  if (value is Map) {
    return value
        .map((k, v) => MapEntry(keyParser!(k) as K, valueParser!(v) as V));
  } else if (value is Iterable) {
    return Map.fromEntries(value
        .map((e) => parseMapEntry<K, V>(e,
            keyParser: keyParser, valueParser: valueParser))
        .whereNotNull());
  } else {
    var s = '$value'.trim();
    if (s.isEmpty) return def;

    var pairs = s.split(_regexpPairDelimiter);
    return Map.fromEntries(pairs
        .map((e) => parseMapEntry<K, V>(e,
            keyParser: keyParser, valueParser: valueParser))
        .whereNotNull());
  }
}