letMapOrNull<K, V> function

Map<K, V>? letMapOrNull<K, V>(
  1. dynamic input, {
  2. bool filterNulls = false,
  3. dynamic nullFallback,
})

Let's you convert input to a Map type if possible, or returns null if the conversion cannot be performed.

If filterNulls is true, the returned map will not contain any null keys or values. If nullFallback is provided, it will be used as a fallback value for null keys and values.

Implementation

Map<K, V>? letMapOrNull<K, V>(
  dynamic input, {
  bool filterNulls = false,
  dynamic nullFallback,
}) {
  dynamic decoded;
  try {
    if (input is String) {
      final trimmed = input.trim();
      if (trimmed.isEmpty) return const {};
      decoded = const JsonDecoder().convert(trimmed);
    } else {
      decoded = input;
    }
    if (decoded is Map) {
      final temp = decoded.entries
          .map((entry) {
            final convertedKey = letOrNull<K>(entry.key);
            final convertedValue =
                letOrNull<V>(entry.value) ?? letOrNull<V?>(nullFallback);
            if (filterNulls) {
              if (!isNullable<K>() && convertedKey == null) {
                return const _Empty();
              }
              if (!isNullable<V>() && convertedValue == null) {
                return const _Empty();
              }
            }
            return MapEntry(convertedKey as K, convertedValue as V);
          })
          .where((e) => e != const _Empty())
          .map((e) => e as MapEntry<K, V>);
      return Map.fromEntries(temp.nonNulls);
    }
  } catch (_) {}
  return null;
}