Skip to content

Instantly share code, notes, and snippets.

@etherealHero
Last active May 20, 2024 13:43
Show Gist options
  • Save etherealHero/41cfa7487e184e656e0c4b71dd7ec480 to your computer and use it in GitHub Desktop.
Save etherealHero/41cfa7487e184e656e0c4b71dd7ec480 to your computer and use it in GitHub Desktop.
freezed & isar & isarLinks
import 'package:flutter/material.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:isar/isar.dart';
import 'package:path_provider/path_provider.dart';
part 'test.freezed.dart';
part 'test.g.dart';
@freezed
@Collection(ignore: {'copyWith'})
class Teacher with _$Teacher {
const Teacher._();
const factory Teacher({
int? id,
required String name,
}) = _Teacher;
@override
// ignore: recursive_getters
Id? get id => id;
}
@freezed
@Collection(ignore: {'copyWith'})
class Student with _$Student {
Student._();
factory Student({
int? id,
required String name,
}) = _Student;
@override
// ignore: recursive_getters
Id? get id => id;
final teachers = IsarLinks<Teacher>();
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final isar = await Isar.open(
[TeacherSchema, StudentSchema],
name: 'test',
directory: (await getApplicationDocumentsDirectory()).path,
);
var teacher1 = const Teacher(name: 'Ann');
var teacher2 = const Teacher(name: 'John');
final student = Student(name: 'Joe');
await isar.writeTxn(() async {
var id1 = await isar.teachers.put(teacher1);
var id2 = await isar.teachers.put(teacher2);
teacher1 = teacher1.copyWith(id: id1);
teacher2 = teacher2.copyWith(id: id2);
student.teachers.addAll([teacher1, teacher2]);
await isar.students.put(student);
await student.teachers.save();
});
final dbStudent = (await isar.students.where().findAll())[0];
await dbStudent.teachers.load();
print(dbStudent.teachers);
}
/// project struct:
/// ```sh
/// project/
/// ├── ...
/// ├── test/
/// │ ├── test.dart
/// │ ├── test.freezed.dart
/// │ └── test.g.dart
/// └── pubspec.yaml
/// ```
///
/// run code generator
/// ```sh
/// dart run build_runner build --delete-conflicting-outputs
/// ```
///
/// package versions where test passed & valid pubspec.yaml:
/// ```yaml
/// environment:
/// sdk: '>=3.3.3 <4.0.0'
/// dependencies:
/// freezed_annotation: ^2.4.1
/// isar_flutter_libs: ^3.1.0+1
/// path_provider: ^2.1.3
/// isar: ^3.1.0+1
/// dev_dependencies:
/// isar_generator: ^3.1.0+1
/// build_runner: ^2.4.9
/// freezed: ^2.5.2
/// flutter_lints: ^3.0.0
/// ```
void hoverMe() {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment