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 key | Dart type to use | Stored as | Notes |
|---|---|---|---|
datetime | DateTime / DateTime? | DateTime or ISO-8601 string (driver-dependent) | Supports CarbonInterface for input. Decodes to DateTime. |
json | Map<String, Object?> / Map<String, Object?>? | JSON string | For JSON objects |
object | Map<String, Object?> / Map<String, Object?>? | JSON string | Alias for json |
array | List<Object?> / List<Object?>? | JSON string | For JSON arrays |
Defining casts
- Model-level casts
- Field-level 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;
}
(table: 'field_cast_settings')
class FieldCastSettings extends Model<FieldCastSettings> {
const FieldCastSettings({required this.id, this.metadata});
(isPrimaryKey: true, autoIncrement: true)
final int id;
(cast: 'json')
final Map<String, Object?>? metadata;
}
Precedence
When multiple options are present, Ormed resolves the codec in this order:
@OrmField(codec: SomeCodecType)(explicit codec type)@OrmField(cast: 'someKey')@OrmModel(casts: {'fieldName': 'someKey'})- 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.
- Codec
- Register
- Use in model
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);
}
DataSource buildDataSource(DriverAdapter driver) {
return DataSource(
DataSourceOptions(
driver: driver,
entities: [
SettingsOrmDefinition.definition,
FieldCastSettingsOrmDefinition.definition,
LinkOrmDefinition.definition,
],
codecs: {'uri': const UriCodec()},
),
);
}
(table: 'links', casts: {'website': 'uri'})
class Link extends Model<Link> {
const Link({required this.id, this.website});
(isPrimaryKey: true, autoIncrement: true)
final int id;
final Uri? website;
}