Skip to main content

Casting

Casting lets you map a model field to a codec key (a string) so Ormed can consistently encode values to the database and decode values back into Dart.

You can define casts:

  • Per-model with @OrmModel(casts: {...})
  • Per-field with @OrmField(cast: '...')

Built-in cast keys

These keys are available out of the box:

Cast keyDart type to useStored asNotes
datetimeDateTime / DateTime?DateTime or ISO-8601 string (driver-dependent)Supports CarbonInterface for input. Decodes to DateTime.
jsonMap<String, Object?> / Map<String, Object?>?JSON stringFor JSON objects
objectMap<String, Object?> / Map<String, Object?>?JSON stringAlias for json
arrayList<Object?> / List<Object?>?JSON stringFor JSON arrays

Defining casts

(
table: 'settings',
casts: {
// Stored as JSON string, read as Map<String, Object?>
'metadata': 'json',
// Stored/read as DateTime (or parsed from ISO-8601 string)
'createdAt': 'datetime',
},
)
class Settings extends Model<Settings> {
const Settings({required this.id, this.metadata, this.createdAt});

(isPrimaryKey: true, autoIncrement: true)
final int id;

final Map<String, Object?>? metadata;
final DateTime? createdAt;
}

Precedence

When multiple options are present, Ormed resolves the codec in this order:

  1. @OrmField(codec: SomeCodecType) (explicit codec type)
  2. @OrmField(cast: 'someKey')
  3. @OrmModel(casts: {'fieldName': 'someKey'})
  4. Default based on the field Dart type (e.g. DateTime)

Custom cast keys (custom codecs)

You can define your own cast keys by registering a codec under that key, then referencing the key from casts / cast.

class UriCodec extends ValueCodec<Uri> {
const UriCodec();


Object? encode(Uri? value) => value?.toString();


Uri? decode(Object? value) =>
value == null ? null : Uri.parse(value as String);
}