tryToMap<K, V> static method
Attempts to convert an object to a Map with keys of type K
and values of type V
.
- If the object is already a Map with the correct key and value types, it is returned as-is.
- If the object is an empty Map, an empty Map is returned.
- If the object is null, returns null.
- If the object cannot be converted to a Map with the specified types, logs an error and returns null.
object
The object to be converted to a Map with keys of type K
and values of type V
.
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 Map<K, V> if conversion is successful, otherwise null.
Example usage:
final object1 = {'key1': 'value1', 'key2': 'value2'};
final map1 = ConvertObject.tryToMap<String, String>(object1); // {'key1': 'value1', 'key2': 'value2'}
final object2 = {'key1': 1, 'key2': 2};
final map2 = ConvertObject.tryToMap<String, int>(object2); // {'key1': 1, 'key2': 2}
final object3 = 'Hello';
final map3 = ConvertObject.tryToMap<String, int>(object3); // null (logs an error)
final object4 = null;
final map4 = ConvertObject.tryToMap<String, int>(object4); // null
Implementation
static Map<K, V>? tryToMap<K, V>(
dynamic object, {
dynamic mapKey,
int? listIndex,
}) {
if (object is String) return tryToMap(object.decode());
if (object is Map && object.isEmpty) return <K, V>{};
if (listIndex != null && object is List<dynamic>) {
return tryToMap(object.of(listIndex));
}
if (mapKey != null && object is Map<dynamic, dynamic>) {
return tryToMap(object[mapKey]);
}
if (object is Map<K, V>?) return object;
try {
return object as Map<K, V>;
} catch (_) {}
try {
return (object as Map)
.map((key, value) => MapEntry(key as K, value as V));
} catch (e, s) {
log(
'tryToMap() Unsupported Map type <$K, $V>: exception message -> $e',
stackTrace: s,
error: e,
);
}
return null;
}