setAttribute method

void setAttribute(
  1. String key,
  2. dynamic value
)

Set an attribute on the model.

Handles type conversion for storage:

  • Carbon values are converted to ISO 8601 strings
  • Map values for json casts are encoded to strings

Implementation

void setAttribute(String key, dynamic value) {
  final castType = casts[key];

  // The raw value is about to change, so any memoised cast or materialised
  // relation built from it is stale. Dropping them here rather than
  // recomputing keeps the write path free of work a reader may never ask for.
  _castCache.remove(key);
  _relationCache.remove(key);

  if (castType is CastsAttributes) {
    _attributes[key] = castType.set(this, key, value);
    return;
  }

  // Convert types for storage
  if (value is Carbon) {
    _attributes[key] = value.format('yyyy-MM-ddTHH:mm:ss');
  } else if (value is DateTime) {
    _attributes[key] = Carbon.fromDateTime(
      value,
    ).format('yyyy-MM-ddTHH:mm:ss');
  } else if (castType == 'json' && (value is Map || value is List)) {
    _attributes[key] = jsonEncode(value);
  } else {
    _attributes[key] = value;
  }
}