toMap<K, V> function
Converts 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, throws a
ParsingException
with anullObject
error. - If the object cannot be converted to a Map with the specified types, throws a
ParsingException
.
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.
Throws a ParsingException
if the conversion fails.
Example usage:
final object1 = {'key1': 'value1', 'key2': 'value2'};
final map1 = toMap<String, String>(object1); // {'key1': 'value1', 'key2': 'value2'}
final object2 = {'key1': 1, 'key2': 2};
final map2 = toMap<String, int>(object2); // {'key1': 1, 'key2': 2'}
final object3 = 'Hello';
final map3 = toMap<String, int>(object3); // ParsingException (logs an error)
final object4 = null;
final map4 = toMap<String, int>(object4); // ParsingException (null object)
Implementation
Map<K, V> toMap<K, V>(
dynamic object, {
Object? mapKey,
int? listIndex,
}) =>
ConvertObject.toMap(object, mapKey: mapKey, listIndex: listIndex);