asT<T extends Object?> method

T? asT<T extends Object?>(
  1. dynamic value
)

Implementation

T? asT<T extends Object?>(dynamic value) {
  if (value is T) {
    return value;
  }
  final String type = T.toString();
  try {
    final String valueS = value.toString();
    if (type == "String") {
      return valueS as T;
    } else if (type == "int") {
      final int? intValue = int.tryParse(valueS);
      if (intValue == null) {
        return double.tryParse(valueS)?.toInt() as T?;
      } else {
        return intValue as T;
      }
    } else if (type == "double") {
      return double.parse(valueS) as T;
    } else if (type == "DateTime") {
      return DateTime.parse(valueS) as T;
    } else if (type == "bool") {
      if (valueS == '0' || valueS == '1') {
        return (valueS == '1') as T;
      }
      return (valueS == 'true') as T;
    } else if (type == "Map" || type.startsWith("Map<")) {
      return value as T;
    } else {
      if (_convertFuncMap.containsKey(type)) {
        return _convertFuncMap[type]!(value) as T;
      } else {
        throw UnimplementedError('$type unimplemented');
      }
    }
  } catch (e, stackTrace) {
    debugPrint('asT<$T> $e $stackTrace');
    return null;
  }
}