toSet<T> static method

Set<T> toSet<T>(
  1. dynamic object, {
  2. dynamic mapKey,
  3. int? listIndex,
})

Converts an object to a Set of type T.

  • If the object is already a Set of type T, it is returned as-is.
  • If the object is an Iterable, it converts it to a Set of type T.
  • If the object is null, throws a ParsingException with a nullObject error.
  • If the object cannot be converted to a Set of type T, throws a ParsingException.

object The object to be converted to a Set of type T. mapKey (Optional) Specifies the key to extract values from a Map object. listIndex (Optional) Specifies the index to extract elements from a List object.

Returns a Set of type T if conversion is successful. Throws a ParsingException if the conversion fails.

Example usage:

final object1 = {1, 2, 3};
final set1 = ConvertObject.toSet<int>(object1); // {1, 2, 3}

final object2 = [1, 2, 3];
final set2 = ConvertObject.toSet<int>(object2); // {1, 2, 3}

final object3 = 'Hello';
final set3 = ConvertObject.toSet<int>(object3); // ParsingException (logs an error)

final object4 = null;
final set4 = ConvertObject.toSet<int>(object4); // ParsingException (null object)

Implementation

static Set<T> toSet<T>(
  dynamic object, {
  dynamic mapKey,
  int? listIndex,
}) {
  if (object == null) {
    throw ParsingException.nullObject(
      parsingInfo: 'toSet',
      stackTrace: StackTrace.current,
    );
  }
  if (object is String) return toSet(object.decode());
  if (object is Iterable && object.isEmpty) return <T>{};
  if (listIndex != null && object is List<dynamic>) {
    return toSet<T>(object.of(listIndex));
  }
  if (mapKey != null && object is Map<dynamic, dynamic>) {
    return toSet<T>(object[mapKey]);
  }
  if (object is Set<T>) return object;
  if (object is T) return <T>{object};
  if (object is Map<dynamic, T>) return object.values.toSet();
  try {
    return (object as Iterable)
        .map((tmp) => tmp is T ? tmp : toType<T>(tmp))
        .toSet();
  } catch (e, s) {
    log(
      'toSet() Unsupported object type ($T): exception message -> $e',
      stackTrace: s,
      error: e,
    );
    throw ParsingException(
      error: e.toString(),
      parsingInfo: 'toSet',
      stackTrace: s,
    );
  }
}