convertTo<T> method

  1. @override
Object? convertTo<T>(
  1. Object? source,
  2. Class targetType, [
  3. Class? sourceType
])
override

Converts the source object from a known sourceType to a targetType using full type metadata via Class.

This method provides the most powerful form of type conversion and supports deep, generic-aware resolution.

Example:

final source = {'date': '2025-07-01'};

final targetType = Class.mapOf(Class<String>(), Class<DateTime>());
final result = service.convertTo(source, Class.forObject(source), targetType);

Implementation

@override
Object? convertTo<T>(Object? source, Class targetType, [Class? sourceType]) {
  sourceType ??= (source != null ? _getSourceType(source) : null);
  if (sourceType == null) {
    if (source != null) {
      throw ConversionException('Source must be [null] if source type == [null]');
    }
    return _handleResult<T>(null, targetType, _convertNullableSource(null, targetType));
  }

  if (source != null && !sourceType.isInstance(source)) {
    throw ConversionException('Source to convert from must be an instance of [$sourceType]; instead it was a [${source.runtimeType}]');
  }

  final converter = _getConverter(sourceType, targetType);
  if (converter != null) {
    final result = ConversionUtils.invoke<T>(converter, source, sourceType, targetType);
    return _handleResult<T>(sourceType, targetType, result);
  }

  return _handleConverterNotFound<T>(source, sourceType, targetType);
}