addConverter<S, T> method

  1. @override
void addConverter<S, T>(
  1. T? converter(
    1. S source
    )
)
override

Adds converter from S to exactly T; it also serves the nullable target T?.

A source is accepted when it is an S, so a converter from num also takes int values. A later registration for the same target wins over an earlier one. The converter may return null (for a blank string, for example); that is accepted only for nullable targets. An error it throws reaches the caller wrapped in a ConversionFailedException.

registry.addConverter<String, Money>(Money.parse);

Implementation

@override
void addConverter<S, T>(T? Function(S source) converter) {
  final entry = _Converter(
    (source) => source is S,
    <X>() => <X>[] is List<S>,
    (s) => converter(s as S),
  );
  // Same converter for `T` and `T?`; newest first (later registrations win).
  _target<T>().converters.insert(0, entry);
  _targets
      .putIfAbsent(
        _typeOf<T?>(),
        () => _Target((v) => v is T?, <X>() => <X>[] is List<T?>),
      )
      .converters
      .insert(0, entry);
}