toMap<T> static method

Map<dynamic, T> toMap<T>(
  1. dynamic value, {
  2. ValueConverter<T>? converter,
  3. EntryConverter<T>? entryConverter,
  4. bool hardCast = false,
})

Tries to parse value into Map.

List, Map, Iterable.

Use converter or entryConverter to convert values. Use hardCast if you are sure that value contains expected Types and there is no need to convert items.

Implementation

static Map<dynamic, T> toMap<T>(dynamic value,
    {ValueConverter<T>? converter,
    EntryConverter<T>? entryConverter,
    bool hardCast = false}) {
  final items = Map<dynamic, T>();

  if (value == null) {
    return items;
  }

  if (value is Iterable) {
    value = value.toList().asMap();
  }

  if (value is Map) {
    if (converter != null) {
      value.forEach((key, item) {
        final mapItem = convert(item, converter: converter);

        if (mapItem != null) {
          items[key] = mapItem;
        }
      });
    } else if (entryConverter != null) {
      value.forEach((key, item) {
        final mapItem = convertEntry(key, item, converter: entryConverter);

        if (mapItem != null) {
          items[key] = mapItem;
        }
      });
    } else {
      if (hardCast) {
        try {
          return value.cast<dynamic, T>();
        } catch (err) {
          printDebug(err.toString());
        }
      }

      value.forEach((key, item) {
        if (item is T) {
          items[key] = item;
        }
      });
    }
  } else {
    if (converter != null) {
      final listItem = convert(value, converter: converter);

      if (listItem != null) {
        items[0] = listItem;
      }
    } else if (entryConverter != null) {
      final listItem = convertEntry(0, value, converter: entryConverter);

      if (listItem != null) {
        items[0] = listItem;
      }
    } else {
      if (value is T) {
        items[0] = value;
      }
    }
  }

  return items;
}