Realm Generator는 Flutter 및 Dart 프로젝트에서 Realm 데이터 모델 정의로부터 자동으로 RealmObject 클래스를 생성하는 코드 생성 도구입니다. 공식 Realm SDK의 일부로서, Realm의 지속적 저장소와 함께 작업하기 위한 타입 안전하고 최적화된 클래스를 생성함으로써 데이터베이스 스키마 관리를 단순화합니다. 이 생성기는 모델과 하위 데이터베이스 구조 간의 일관성을 보장하여 반복 코드를 줄이고 런타임 오류를 최소화합니다. Flutter의 pub 시스템을 통해 빌드 프로세스에 원활하게 통합됩니다.
사용 사례
데이터 모델에서 RealmObject 클래스를 자동으로 생성합니다
Flutter 앱에서 데이터베이스 스키마 정의 간소화
지속 데이터 클래스의 수동 코드 작성 감소
Realm 기반 데이터 접근에서 타입 안정성 보장
Realm 데이터베이스에서 복잡한 객체 관계 지원
주요 기능
모델 정의에서 RealmObject 클래스 생성
Flutter 빌드 시스템과 통합
유형 안전하고 최적화된 코드를 생성합니다
중첩된 개체 및 관계를 지원합니다
컴파일 시점에서 스키마 일관성 강제
적합한 대상
로컬 지속성에 Realm을 사용하는 Flutter 개발자
데이터 저장에서 강력한 타이핑과 성능이 필요한 프로젝트
데이터베이스 모델에서 부울러플레이트를 최소화하고자 하는 팀
복잡한 데이터 구조를 가진 앱에서 신뢰할 수 있는 스키마 관리가 필요한 경우
고려 사항
Realm SDK 사용이 필요합니다
pubspec.yaml에 올바른 설정이 필요합니다
빌드 시 종속성; 런타임에 사용할 수 없음
사용자 정의 필드에 대한 추가 구성이 필요할 수 있습니다
영역 고유의 데이터 모델링 접근 방식에 제한됨
원본 README
연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.
[!WARNING]
We announced the deprecation of Atlas Device Sync + Realm SDKs in September 2024. For more information please see:
For a version of realm-dart without sync features, install version 20 or see the community branch.
Realm is a mobile database that runs directly inside phones, tablets or wearables.
This repository holds the source code for the Realm SDK for Flutter™ and Dart™.
Features
Mobile-first: Realm is the first database built from the ground up to run directly inside phones, tablets, and wearables.
Simple: Realm’s object-oriented data model is simple to learn, doesn’t need an ORM, and the API lets you write less code to get apps up & running in minutes.
Modern: Realm supports latest Dart and Flutter versions and is built with sound null-safety.
Fast: Realm is faster than even raw SQLite on common operations while maintaining an extremely rich feature set.
import'package:realm/realm.dart'; // import realm packagepart'app.realm.dart'; // declare a part file.@RealmModel() // define a data model class named `_Car`.class_Car{
lateString make;
lateString model;
int? kilometers = 500;
}
Generate RealmObject class Car from data model class _Car.
dart run realm generate
Open a Realm and add some objects.
var config = Configuration.local([Car.schema]);
var realm = Realm(config);
var car = Car("Tesla", "Model Y", kilometers: 5);
realm.write(() {
realm.add(car);
});
Query objects in Realm.
var cars = realm.all<Car>();
Car myCar = cars[0];
print("My car is ${myCar.make} model ${myCar.model}");
cars = realm.all<Car>().query("make == 'Tesla'");
Generate RealmObject class Item from data model class _Item.
On Flutter use dart run realm to run realm package commands
dart run realm generate
A new file catalog.realm.dart will be created next to the catalog.dart.
*The generated file should be committed to source control
Use the RealmObject class Item with Realm.
// Create a Configuration objectvar config = Configuration.local([Item.schema]);
// Opean a Realmvar realm = Realm(config);
var myItem = Item(0, 'Pen', price: 4);
// Open a write transaction
realm.write(() {
realm.add(myItem);
var item = realm.add(Item(1, 'Pencil')..price = 20);
});
// Objects `myItem` and `item` are now managed and persisted in the realm// Read object properties from realmprint(myItem.name);
print(myItem.price);
// Update object properties
realm.write(() {
myItem.price = 20;
myItem.name = "Special Pencil";
});
// Get objects from the realm// Get all objects of typevar items = realm.all<Item>();
// Get object by indexvar item = items[1];
// Get object by primary keyvar itemByKey = realm.find<Item>(0);
// Filter and sort objectvar objects = realm.query<Item>("name == 'Special Pencil'");
var name = 'Pen';
objects = realm.query<Item>(r'name == $0', [name]);
// Close the realm
realm.close();
Full contents of catalog.dart
import'package:realm/realm.dart';
part'catalog.realm.dart';
@RealmModel()
class_Item{
@PrimaryKey()
lateint id;
lateString name;
int price = 42;
}
// Create a Configuration objectvar config = Configuration.local([Item.schema]);
// Open a Realmvar realm = Realm(config);
var myItem = Item(0, 'Pen', price: 4);
// Open a write transaction
realm.write(() {
realm.add(myItem);
var item = realm.add(Item(1, 'Pencil')..price = 20);
});
// Objects `myItem` and `item` are now managed and persisted in the realm// Read object properties from realmprint(myItem.name);
print(myItem.price);
// Update object properties
realm.write(() {
myItem.price = 20;
myItem.name = "Special Pencil";
});
// Get objects from the realm// Get all objects of typevar items = realm.all<Item>();
// Get object by indexvar item = items[1];
// Get object by primary keyvar itemByKey = realm.find<Item>(0);
// Filter and sort objectvar objects = realm.query<Item>("name == 'Special Pencil'");
var name = 'Pen';
objects = realm.query<Item>(r'name == $0', [name]);
// Close the realm
realm.close();
Initialize the App Services App client and authenticate a user.
String appId = "<Atlas App ID>";
final appConfig = AppConfiguration(appId);
final app = App(appConfig);
final user = await app.logIn(Credentials.anonymous());
Open a synced realm.
final config = Configuration.flexibleSync(user, [Task.schema]);
final realm = Realm(config);
Add a sync subscription and write data.
Only data matching the query in the subscription will be synced to the server and only data matching the subscription will be downloaded to the local device realm file.
realm.subscriptions.update((mutableSubscriptions) {
mutableSubscriptions.add(realm.query<Task>(r'status == $0 AND progressMinutes == $1', ["completed", 100]));
});
await realm.subscriptions.waitForSynchronization();
realm.write(() {
realm.add(Task(ObjectId(), "Send an email", "completed", 4));
realm.add(Task(ObjectId(), "Create a meeting", "completed", 100));
realm.add(Task(ObjectId(), "Call the manager", "init", 2));
});
realm.close();
See CONTRIBUTING.md for instructions about building the source.
Code of Conduct
This project adheres to the MongoDB Code of Conduct.
By participating, you are expected to uphold this code. Please report
unacceptable behavior to [community-conduct@mongodb.com](mailto:community-conduct@mongodb.com).
License
Realm Flutter and Dart SDKs and Realm Core are published under the Apache License 2.0.
The "Dart" name and logo and the "Flutter" name and logo are trademarks owned by Google.