tryToList<T> function
Attempts to convert an object to a List of type T
, or returns null
if conversion is not possible.
mirroring the same static method in the ConvertObject, providing alternative easy less code usage options.
- If the object is already a List of type
T
, it is returned as-is. - If the object is a single instance of type
T
, it returns a List containing that object. - If the object is a Map, and
mapKey
is provided, it returns a List of the values for that key across all map entries. - If the object is a Map with values of type
T
and nomapKey
is provided, it returns a List of all the map's values. - If the object is a List, and
listIndex
is provided, it attempts to return a List containing the element at that index from each list in the original list. - If the object cannot be converted to a List of type
T
, an error is logged, andnull
is returned.
object
The object to be converted to a List 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 List of type T
if conversion is successful, otherwise null
.
Example usage:
final object1 = [1, 2, 3];
final list1 = tryToList<int>(object1); // [1, 2, 3]
final object2 = 42;
final list2 = tryToList<int>(object2); // [42]
final object3 = {'a': 1, 'b': 2};
final list3 = tryToList<int>(object3); // [1, 2]
final object4 = {'a': [1, 2], 'b': [3, 4]};
final list4 = tryToList<int>(object4, mapKey: 'a'); // [1, 2]
final object5 = [[1, 2], [3, 4]];
final list5 = tryToList<int>(object5, listIndex: 0); // [1, 3]
final object6 = 'Hello';
final list6 = tryToList<int>(object6); // null (logs an error)
final object7 = null;
final list7 = tryToList<int>(object7); // null
Implementation
List<T>? tryToList<T>(
dynamic object, {
Object? mapKey,
int? listIndex,
}) =>
ConvertObject.tryToList(object, mapKey: mapKey, listIndex: listIndex);