convert<T> method
A general-purpose converter that can convert between multiple source–target type pairs.
This interface allows conversion logic to be shared across multiple type mappings, and optionally exposes the set of convertible type pairs.
đź”§ Example:
class MyConverter implements PairedConverter {
@override
Set<ConvertiblePair> getConvertibleTypes() => {
ConvertiblePair(Class<String>(), Class<int>())
};
@override
Object? convert(Object? source, Class sourceType, Class targetType) {
if (source is String && targetType.getType() == int) {
return int.tryParse(source);
}
return null;
}
}
Converts the source object from sourceType to targetType.
Returns the converted value or null if the conversion fails or is unsupported.
Implementation
@override
Object? convert<T>(Object? source, Class sourceType, Class targetType) {
if (source == null) return null;
final targetElementType = targetType.componentType();
if (targetElementType != null && targetElementType.isInstance(source)) {
return [source];
}
if (targetElementType != null) {
final convertedElement = _conversionService.convertTo(source, targetElementType, sourceType);
return [convertedElement];
}
return [source];
}