您可以使用注解为 Realm 对象模型中的属性添加功能。
必要属性和可选属性
在Dart中,值类型隐式不可为 null,但可通过附加 ? 。包含?
以使属性成为可选属性。
class _Vehicle { () late ObjectId id; late String? maybeDescription; // optional value late double milesTravelled = 0; // 0 is default value () late String notInRealmModel; () late String make; 'wheels') // 'wheels' is property name in the RealmObject ( late int numberOfWheels; }
默认字段值
您可以使用内置语言功能为属性指定默认值。在属性声明中指定默认值。
class _Vehicle { () late ObjectId id; late String? maybeDescription; // optional value late double milesTravelled = 0; // 0 is default value () late String notInRealmModel; () late String make; 'wheels') // 'wheels' is property name in the RealmObject ( late int numberOfWheels; }
主键
PrimaryKey 注释指示主键属性。主键是域中对象的唯一标识符。同一类型的其他对象不能股票对象的主键。
主键的重要方面:
将对象添加到 Realm 后,您无法更改主键。
仅向 RealmModel 中的一个属性添加主键。
只有
String
、int
、ObjectId
和Uuid
类型可以作为主键。Realm 会自动索引主键。
主键可为 null。
null
只能是集合中一个对象的主键。
class _Vehicle { () late ObjectId id; late String? maybeDescription; // optional value late double milesTravelled = 0; // 0 is default value () late String notInRealmModel; () late String make; 'wheels') // 'wheels' is property name in the RealmObject ( late int numberOfWheels; }
将属性或类映射到其他名称
MapTo 注解指示模型或属性应以不同名称持久保存。跨不同绑定打开Realm时,在这些绑定中,代码样式约定可能不同,这非常有用。示例:
要便于在具有不同命名约定的多个平台上工作。例如,如果 Device Sync 模式属性名称使用蛇形大小写,而项目使用驼峰大小写。
在不强制迁移的情况下更改类名或字段名。
()'naval_ship') (class _Boat { () late ObjectId id; late String name; late int? maxKnots; late int? nauticalMiles; }
class _Vehicle { () late ObjectId id; late String? maybeDescription; // optional value late double milesTravelled = 0; // 0 is default value () late String notInRealmModel; () late String make; 'wheels') // 'wheels' is property name in the RealmObject ( late int numberOfWheels; }
忽略来自 Realm 模式的属性
如果您将 Ignored 注解添加到RealmModel
中的某个属性,则域对象生成器不会将该属性包含在RealmObject
模式中,也不会持久保存到Realm中。
class _Vehicle { () late ObjectId id; late String? maybeDescription; // optional value late double milesTravelled = 0; // 0 is default value () late String notInRealmModel; () late String make; 'wheels') // 'wheels' is property name in the RealmObject ( late int numberOfWheels; }
索引属性
添加 Indexed 注解以在字段上创建索引。索引可以大幅加快某些查询的速度,但费用是写入速度稍慢,并增加存储和内存开销。Realm将索引存储在磁盘上,这会使您的域文件更大。每个索引项至少有 12 个字节。索引可为 null。
可对以下数据类型建立索引:
bool
int
String
ObjectId
Uuid
DateTime
RealmValue
class _Vehicle { () late ObjectId id; late String? maybeDescription; // optional value late double milesTravelled = 0; // 0 is default value () late String notInRealmModel; () late String make; 'wheels') // 'wheels' is property name in the RealmObject ( late int numberOfWheels; }
全文搜索索引
除了标准索引外,Realm 还支持对字符串属性创建 Atlas 全文搜索索引。虽然无论是否使用标准索引都可以查询字符串字段,但 FTS 索引支持搜索多个词汇和短语并排除其他。
有关查询 FTS 索引的更多信息,请参阅使用全文搜索进行筛选。
要在属性上创建 FTS索引,请使用 @Indexed 注解并将 RealmIndexType 指定为 fullText
。这将启用对属性的全文查询。在以下示例中,我们使用 FTS 注释来标记模式和材料属性:
()class _Rug { () late ObjectId id; (RealmIndexType.fullText) late String pattern; (RealmIndexType.fullText) late String material; late int softness; }