convert<T> static method

T convert<T>(
  1. dynamic value, {
  2. T? defaultValue,
  3. SuperConverter<T>? converter,
})

convert in case of single item

Implementation

static T convert<T>(
  dynamic value, {
  T? defaultValue,

  /// to use single time used converter
  SuperConverter<T>? converter,
}) {
  if (value is T) return value;

  if (isSubType<List, T>()) throw ListConversionError(type: T, data: value);

  for (var converter in [converter, ..._converters]) {
    if (converter == null) continue;

    if (converter.canHandle<T>()) {
      try {
        return converter.handle(value, defaultValue: defaultValue) ??
            defaultValue;
      } catch (e) {
        if (defaultValue is T) return defaultValue;

        if (e is SuperConvertorException) rethrow;

        throw ConversionError(type: converter.runtimeType, data: value);
      }
    }
  }

  /// try to register your class by using [registerConverters] method
  /// For Enums you can use [EnumConverter]
  /// For Classes you can use [FromMapConverter]
  throw UnKnownConverter(T);
}