getProperty<T> method

T? getProperty<T>(
  1. String name
)

Read a property by name with a runtime type check.

Returns null if the property is absent or stored as null. Empty lists return an empty List, not null. Throws StateError if the stored type does not match T. Reserved names (__key__, __version__) are not exposed and always return null.

Implementation

T? getProperty<T>(String name) {
  if (_isReservedPropertyName(name)) {
    return null;
  }
  final type = propertyType(name);
  if (type == NSPropertyType.none) {
    return null;
  }

  if (type == NSPropertyType.list) {
    final value = _readListProperty(name);
    if (value == null) {
      return null;
    }
    if (value is T) {
      return value as T;
    }
    throw StateError(
      'Property "$name" is ${value.runtimeType}, expected $T',
    );
  }

  final value = _readProperty(name, type);
  if (value == null) {
    return null;
  }
  if (value is T) {
    return value as T;
  }
  throw StateError(
    'Property "$name" is ${value.runtimeType}, expected $T',
  );
}