toType<T> static method

T toType<T>(
  1. TypeCode? type,
  2. dynamic value
)

Converts value into an object type specified by Type Code or returns type default when conversion is not possible.

  • type the TypeCode for the data type into which 'value' is to be converted.
  • value the value to convert. Returns object value of type corresponding to TypeCode, or type default when conversion is not supported.

See toNullableType See toTypeCode

Implementation

static T toType<T>(TypeCode? type, value) {
  // Convert to the specified type
  var result = TypeConverter.toNullableType<T>(type, value);
  if (result != null) return result;

  // Define and return default value based on type
  if (type == TypeCode.Integer) {
    value = 0;
  } else if (type == TypeCode.Long) {
    value = 0;
  } else if (type == TypeCode.Float) {
    value = 0;
  } else if (type == TypeCode.Double) {
    value = 0;
  } else if (type == TypeCode.Boolean) {
    value = false;
  } else if (type == TypeCode.String) {
    value = '';
  } else if (type == TypeCode.DateTime) {
    value = DateTime.now().toUtc();
  } else if (type == TypeCode.Duration) {
    value = Duration();
  } else if (type == TypeCode.Map) {
    value = <String, dynamic>{};
  } else if (type == TypeCode.Array) value = [];

  return value as T;
}