castListToTypes method

List<Object?>? castListToTypes(
  1. String itemType
)

Casts a list of items to the specified type.

Returns null if the casting fails.

Implementation

List<Object?>? castListToTypes(String itemType) {
  if (itemType.startsWith('List<')) {
    // Handle nested lists by recursively parsing the inner type
    final String innerType = itemType.substring(5, itemType.length - 1);
    final List<Object?>? result = deserializeListByType<List<Object?>>();
    if (result == null) return null;

    // Recursively parse each inner list and filter out nulls
    final List<Object?> resultList = result
        .map((Object? list) {
          if (list is List<Object?>) {
            final List<Object?>? parsedList = list.castListToTypes(innerType);
            if (parsedList == null) return null;
            return parsedList.where((Object? e) => e != null).toList();
          }
          return null;
        })
        .where((List<Object?>? list) => list != null)
        .toList();

    // Ensure we have a non-nullable list of non-nullable lists
    return resultList.whereType<List<Object?>>().toList();
  }

  return switch (itemType) {
    'String' => deserializeListByType<String>(),
    'int' => deserializeListByType<int>(),
    'double' => deserializeListByType<double>(),
    'bool' => deserializeListByType<bool>(),
    'DateTime' => deserializeListByType<DateTime>(),
    'Color' => deserializeListByType<Color>(),
    'dynamic' => deserializeListByType<Object?>(),
    'Object' => deserializeListByType<Object>(),
    'Object?' => deserializeListByType<Object?>(),
    _ => throw UnimplementedError(
      'The list item type $itemType is not supported',
    ),
  };
}