get<T> method

T get<T>(
  1. String key, {
  2. T? def,
})

Retrieves a value of type T associated with the specified key. If the key contains '/', it treats the key as a path and navigates through the nested structure to retrieve the value. If the key does not exist, returns the provided default value def. Supports basic types such as int, String, bool, List, and DateTime. key The key or path whose associated value is to be retrieved. def A default value of type T that is returned if the key does not exist. Returns the value associated with the key, or the default value if the key does not exist.

Implementation

T get<T>(String key, {T? def}) {
  if (key.contains('/')) {
    return getByPathString<T>(key);
  } else {
    if (this[key] == null) {
      return def as T;
    }
    if (T == String) {
      if (this[key].toString().isEmpty) return (def ?? '') as T;
      return this[key].toString() as T;
    }
    if (T == int) {
      var res = int.tryParse(this[key].toString());
      if (res != null) {
        return res as T;
      }
      return def as T;
    }

    if (T == List) {
      if (this[key] is T) {
        return this[key] as T;
      } else {
        return def as T;
      }
    }

    if (T == DateTime) {
      if (this[key] is T) {
        return this[key] as T;
      } else {
        return def as T;
      }
    }

    if (T == bool) {
      if (this[key] is String) {
        return this[key].toString().toBool as T;
      } else if (this[key] is T) {
        return this[key] as T;
      } else if (this[key] == null && def == null) {
        return false as T;
      } else {
        return def as T;
      }
    }

    return this[key] as T;
  }
}