tryToMap<K, V> function
Attempts to convert an object to a Map with keys of type K
and values of type V
.
mirroring the same static method in the ConvertObject, providing alternative easy less code usage options.
- 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 = tryToMap<String, String>(object1); // {'key1': 'value1', 'key2': 'value2'}
final object2 = {'key1': 1, 'key2': 2};
final map2 = tryToMap<String, int>(object2); // {'key1': 1, 'key2': 2}
final object3 = 'Hello';
final map3 = tryToMap<String, int>(object3); // null (logs an error)
final object4 = null;
final map4 = tryToMap<String, int>(object4); // null
Implementation
Map<K, V>? tryToMap<K, V>(
dynamic object, {
Object? mapKey,
int? listIndex,
}) =>
ConvertObject.tryToMap(object, mapKey: mapKey, listIndex: listIndex);