convertValueIfNecessary<T> method
Convert a given value
into the specified targetType
if necessary.
This method uses a ConversionService
to handle type conversions.
If no conversion service is explicitly set, it falls back to
DefaultConversionService.getSharedInstance
.
If the targetType
is null
, the value is simply cast to T
.
Parameters
value
: The input object to convert.targetType
: The desired target type.source
: An optionalClass
describing the source type (used for conversion context).
Example
final result = convertValueIfNecessary<int>('42', Class<int>(null, 'dart'));
print(result); // 42
Implementation
T? convertValueIfNecessary<T>(Object value, Class<T>? targetType, [Class? source]) {
if (targetType == null) {
return value as T;
}
ConversionService? conversionServiceToUse = _conversionService;
if (conversionServiceToUse == null) {
// Avoid initialization of shared DefaultConversionService if
// no standard type conversion is needed in the first place...
if (targetType.isInstance(value)) {
return value as T;
}
conversionServiceToUse = DefaultConversionService.getSharedInstance();
}
return conversionServiceToUse.convert<T>(value, targetType, source?.getQualifiedName());
}