tryToSet<T> static method
Attempts to convert an object to a Set of type T
, or returns null if conversion is not possible.
- 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, returns null.
- If the object cannot be converted to a Set of type
T
, logs an error and returns null.
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, otherwise null.
Example usage:
final object1 = {1, 2, 3};
final set1 = ConvertObject.tryToSet<int>(object1); // {1, 2, 3}
final object2 = [1, 2, 3];
final set2 = ConvertObject.tryToSet<int>(object2); // {1, 2, 3}
final object3 = 'Hello';
final set3 = ConvertObject.tryToSet<int>(object3); // null (logs an error)
final object4 = null;
final set4 = ConvertObject.tryToSet<int>(object4); // null
Implementation
static Set<T>? tryToSet<T>(
dynamic object, {
dynamic mapKey,
int? listIndex,
}) {
if (object is String) return tryToSet(object.decode());
if (object is Iterable && object.isEmpty) return <T>{};
if (listIndex != null && object is List<dynamic>) {
return tryToSet<T>(object.of(listIndex));
}
if (mapKey != null && object is Map<dynamic, dynamic>) {
return tryToSet<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 {
if (mapKey != null && object is Map<dynamic, dynamic>) {
return tryToSet(object[mapKey]);
}
if (object == null) return null;
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,
);
return null;
}
}