converterFor method Null safety
If it exists, get the Converter for a given type.
If no direct converter for the specified Type is found, a FallbackConverter will be assebled with all converters that might be able to provide the requested type indirectly.
If logWarn
is true
, a warning will be issued when using an assembled converter.
Implementation
Converter<dynamic>? converterFor(Type type, {bool logWarn = true}) {
if (_converters.containsKey(type)) {
return _converters[type]!;
}
TypeMirror targetMirror = reflectType(type);
List<Converter<dynamic>> assignable = [];
List<Converter<dynamic>> superClasses = [];
for (final key in _converters.keys) {
TypeMirror keyMirror = reflectType(key);
if (keyMirror.isAssignableTo(targetMirror)) {
assignable.add(_converters[key]!);
} else if (targetMirror.isAssignableTo(keyMirror)) {
superClasses.add(_converters[key]!);
}
}
for (final converter in superClasses) {
// Converters for types that superclass the target type might return an instance of the
// target type.
assignable.add(CombineConverter(converter, (superInstance, context) {
if (reflect(superInstance).type.isAssignableTo(targetMirror)) {
return superInstance;
}
return null;
}));
}
if (assignable.isNotEmpty) {
if (logWarn) {
_commandsLogger
.warning('Using assembled converter for type $type. If this is intentional, you '
'should register a custom converter for that type using '
'`addConverter(converterFor($type, logWarn: false) as Converter<$type>)`');
}
return FallbackConverter(assignable);
}
return null;
}