add<T extends RealmObject> method Null safety

T add<T extends RealmObject>(
  1. T object

Adds a RealmObject to the Realm.

This Realm will start managing the RealmObject. A RealmObject instance can be managed only by one Realm. If the object is already managed by this Realm, this method does nothing. This method modifies the object in-place as it becomes managed. Managed instances are persisted and become live objects. Returns the same instance as managed. This is just meant as a convenience to enable fluent syntax scenarios. Throws RealmException when trying to add objects with the same primary key. Throws RealmException if there is no write transaction created with write.


T add<T extends RealmObject>(T object) {
  if (object.isManaged) {
    return object;

  final metadata = _metadata[object.runtimeType];
  if (metadata == null) {
    throw RealmError("Object type ${object.runtimeType} not configured in the current Realm's schema."
        " Add type ${object.runtimeType} to your config before opening the Realm");

  final handle = metadata.class_.primaryKey == null
      ? realmCore.createRealmObject(this, metadata.class_.key)
      : realmCore.createRealmObjectWithPrimaryKey(this, metadata.class_.key, object.accessor.get(object, metadata.class_.primaryKey!)!);

  final accessor = RealmCoreAccessor(metadata);
  object.manage(this, handle, accessor);

  return object;