cast<T> function

T cast<T>(
  1. dynamic x, {
  2. T? fallback,
  3. String? errorMessage,
})

Implementation

T cast<T>(dynamic x, {T? fallback, String? errorMessage}) {
	final T? result = x is T ? x
		: x == null ? null
		: T == double ? (
			x is int ? x.toDouble() as T
			: x is String ? double.tryParse(x) as T?
			: null
		)
		: T == int ? (
			x is double ? x.toInt() as T
			: x is String ? int.tryParse(x) as T?
			: null
		)
		: T == String ? x.toString() as T?
		: null;
	if (result == null && null is! T) {
		if (fallback != null) return fallback;
		else throw Exception(errorMessage ?? 'Unable to cast from ${x.runtimeType} to $T');
	}
	return result as T;
}