register<S, T> method Null safety

void register<S, T>(
  1. T converter(
    1. S
  2. {Pattern? format}

Registers a conversion function

This registers a converter from source type S to destination type T. The optional format parameter can be used to register a converter for specific formats only. In that case, the converter will only be used when calling with a format parameter that matches this format. The format can be a plain string, in which case it should be an exact match, or a RegExp in which case it will handle any request with a format that matches this regular expression.

When converter has a named optional parameter format, the format parameter used in will be forwarded to this converter.

register<String, DateTime>((String v, {String format}) {
  var f = DateFormat(format);
  return f.parse(v);
}, format: RegExp('.*'));

Converters are applied in reverse order of how they were registered. So, you can (partly) overwrite an already registered converter, by registering a new one.


void register<S, T>(T Function(S) converter, {Pattern? format}) {
  if (isSealed) {
    throw StateError('Cannot register new conversion methods when sealed.');
  _addConverter(_SnapshotDecoderFactory<S, T?>((s, format) {
    if (s == null) return null;
    if (converter is T Function(S, {String? format})) {
      return converter(s, format: format);
    return converter(s);
  }, format));