convertToType method

dynamic convertToType (
  1. Type type,
  2. dynamic value
)

Converts value to type.

Returns null if value is null else value converted to type or just value if conversion failed.

Implementation

static dynamic convertToType(Type type, dynamic value) {
  if (value == null) {
    return null;
  }
  if (type == value.runtimeType) {
    return value;
  }
  if (type == String) {
    return value.toString();
  }
  if (type == bool) {
    if (value.runtimeType == String) {
      String strVal = value;
      if (strVal.toLowerCase() == 'true' || strVal == '1') {
        return true;
      }
      return false;
    }
  } else if (type == int) {
    if (value.runtimeType == String) {
      return int.tryParse(value);
    } else if (value.runtimeType == double) {
      double dval = value;
      return dval.floor();
    }
  } else if (type == double) {
    if (value.runtimeType == int) {
      int intVal = value;
      return intVal.toDouble();
    } else if (value.runtimeType == String) {
      return double.parse(value);
    }
  } else if (type == DateTime) {
    if (value.runtimeType == String) {
      return DateTime.parse(value);
    }
  }
  print(
      'Missing conversion from ${value.runtimeType} $value into type $type');
  return value;
}