deserializeListItems<T> method

T? deserializeListItems<T>()

Safely deserializes a list of items to the specified type T.

Returns null if the deserialization fails.

Implementation

T? deserializeListItems<T>() {
  final String typeString = T.toString();
  final String innerType = typeString.substring(5, typeString.length - 1);

  // Handle nested lists
  if (typeString.startsWith('List<List<')) {
    try {
      // Extract the inner type from the nested list
      final String nestedInnerType = innerType.substring(
        5,
        innerType.length - 1,
      );

      // First convert the outer list
      final List<List<Object?>?> outerList = map((Object? item) {
        if (item is List<Object?>) {
          return item;
        }
        return null;
      }).where((List<Object?>? item) => item != null).toList();

      // Then convert each inner list to the target type
      final List<List<Object?>> result = outerList.map((
        List<Object?>? innerList,
      ) {
        if (innerList == null) return <Object?>[];

        return switch (nestedInnerType) {
          'String' => innerList.whereType<String>().toList(),
          'int' => innerList.whereType<int>().toList(),
          'double' => innerList.whereType<double>().toList(),
          'bool' => innerList.whereType<bool>().toList(),
          'DateTime' => innerList.whereType<DateTime>().toList(),
          'Color' => innerList.whereType<Color>().toList(),
          _ => innerList,
        };
      }).toList();

      return switch (nestedInnerType) {
            'String' => result.cast<List<String>>().toList(),
            'int' => result.cast<List<int>>().toList(),
            'double' => result.cast<List<double>>().toList(),
            'bool' => result.cast<List<bool>>().toList(),
            'DateTime' => result.cast<List<DateTime>>().toList(),
            'Color' => result.cast<List<Color>>().toList(),
            _ => result,
          }
          as T;
    } catch (e, s) {
      safeDebugLog('Error deserializing nested list: $e', stackTrace: s);
      return null;
    }
  }

  // Handle regular lists
  final List<Object?>? result = castListToTypes(innerType);
  if (result == null) return null;

  try {
    return result as T?;
  } catch (e, s) {
    safeDebugLog('Error deserializing list items: $e', stackTrace: s);
    return null;
  }
}