intelligentCast<T> function

T? intelligentCast<T>(
  1. dynamic value
)

This attempts to intelligently cast any value to the desired type.

Implementation

T? intelligentCast<T>(dynamic value) {
  // instead of empty string we want to return null
  if (value.toString().isEmpty) return null;

  // already expected type, return it
  if (value is T) return value;

  // process bool here, since we need to return false rather than null
  if (T.toString() == 'bool') return boolParse(value.toString()) as T;

  // if null, dont change it.
  if (value == null) return null;

  // perform explicit parsing on the value as a string
  if (T.toString() == 'double') return double.parse(value.toString()) as T;
  if (T.toString() == 'double?') return double.parse(value.toString()) as T;
  if (T.toString() == 'int') return int.parse(value.toString()) as T;
  if (T.toString() == 'int?') return int.parse(value.toString()) as T;
  if (T.toString() == 'Color') return colorParse(value) as T;

  throw Exception('Failed to convert $value to $T');
}