addConverter<S, T> method
void
addConverter<S, T>(
- Converter<
S, T> converter, { - Class<
S> ? sourceType, - Class<
T> ? targetType,
override
Registers a simple Converter from one specific source type to one target type.
🔧 Example
registry.addConverter(StringToIntConverter());
registry.addConverter(StringToIntConverter(), sourceType: Class<String>(), targetType: Class<int>());
Implementation
@override
void addConverter<S, T>(Converter<S, T> converter, {Class<S>? sourceType, Class<T>? targetType}) {
if(sourceType != null && targetType != null) {
addPairedConverter(_PairedConverterAdapter(converter, sourceType, targetType, _pd, _convertNullableSource));
} else if(sourceType == null && targetType == null) {
final clazz = converter.getClass(null, converter.getPackageName());
// We'll try to access the [Converter] class as an interface first
List<Class> types = clazz.getDeclaredInterface<Converter>()?.getTypeParameters() ?? [];
// If it fails, we'll try to access it as a superclass
if(types.isEmpty) {
types = clazz.getDeclaredSuperClass()?.getTypeParameters() ?? [];
}
if (types.isEmpty || types.length.isLessThan(2)) {
throw ConversionException(
'Unable to determine source type and target type for your '
'Converter [${converter.runtimeType}]; does the class parameterize those types? If '
'you are using a generic converter, make sure to explicitly specify the source '
'and target types.'
);
}
addPairedConverter(_PairedConverterAdapter(converter, types.getFirst(), types.getLast(), _pd, _convertNullableSource));
}
}