convert function

dynamic convert(
  1. dynamic value,
  2. String typeName, [
  3. TypeContext? context = null
])

Implementation

dynamic convert(dynamic value, String typeName, [TypeContext? context = null]) {
  typeName = trimEnd(typeName, '?'); // test without optional
  if (typeName == "dynamic") {
    Log.warn("convert(): skipping converting '${value.runtimeType}' to 'dynamic' type");
    return value;
  }
  if (typeName == "int") {
    return int.tryParse(_toString(value)!) ?? null;
  }
  if (typeName == "double") {
    return double.tryParse(_toString(value)!) ?? null;
  }
  if (typeName == "String") {
    return _toString(value);
  }
  if (typeName == "bool") {
    if (value is bool) return value;
    var strBool = _toString(value);
    if (strBool == null) return false;
    strBool = strBool.toLowerCase();
    return strBool == "true" || strBool == "t" || strBool == "1";
  }
  if (context != null) {
    var typeInfo = context.getTypeInfo(typeName);
    if (typeInfo != null) {
      if (typeInfo.type == TypeOf.Enum) {
        var o = JsonConverters.enumConverter.fromJson(value, context.newContext(typeName));
        return o;
      } else if (typeInfo.canCreate == true) {
        var o = typeInfo.createInstance();
        if (o is List) {
          var converter = JsonConverters.get("List")!;
          return converter.fromJson(value, context.newContext(typeName));
        } else if (o is Map) {
          var converter = JsonConverters.get("Map")!;
          return converter.fromJson(value, context.newContext(typeName));
        }
        try {
          if (o is IConvertible) {
            o.context = context;
          }
          var ret = o.fromMap(value);
          return ret;
        } catch (e, trace) {
          Log.error("convert(): $e\n$trace", e as Exception?);
          rethrow;
        }
      }
    }
  }
  return value;
}