getByKey method

dynamic getByKey(
  1. dynamic key
)

Retrieves the value associated with key, parsed to an appropriate type.

Parameters

  • key: The key to lookup (integer or string).

Returns

  • null if the key does not exist or the value is null.
  • bool when the stored string is "true" or "false".
  • int when the value can be parsed as an integer.
  • double when the value can be parsed as a floating point number.
  • String when the value cannot be parsed to another primitive type.

Implementation

dynamic getByKey(final dynamic key) {
  if (!_data.containsKey(key)) {
    return null;
  }
  final dynamic value = _data[key];
  if (value != null) {
    if (value == 'true' || value == 'false') {
      return value == 'true';
    }
    try {
      return int.parse(value);
    } catch (e) {
      // Not an int, try parsing as double
      try {
        return double.parse(value);
      } catch (e) {
        // Not a double, return the original string value
        return value;
      }
    }
  }
  return null;
}