T to<T>(dynamic i, {T defaultValue}) {
if (i == null) {
return defaultValue;
}
if (i is T) {
return i;
}
if (i is String) {
switch (T) {
case double:
return (double.tryParse(i) ?? defaultValue) as T;
case int:
return (int.tryParse(i) ?? defaultValue) as T;
case bool:
return ((int.tryParse(i) ?? 0) > 0) as T;
default:
return defaultValue;
}
}
if (i is num) {
switch (T) {
case double:
return (i.toDouble() ?? defaultValue) as T;
case int:
return (i.toInt() ?? defaultValue) as T;
case String:
return '$i' as T;
case bool:
return (i > 0) as T;
default:
return defaultValue;
}
}
return (i is T) ? i : defaultValue;
}