Freezed is a code generator that helps you create immutable, serializable classes in Dart, reduce duplicate code, and improve code readability and maintainability.
Isar is an extremely fast, easy to use, and fully async NoSQL database for Flutter.
Together, Freezed and Isar empower you to:
- Define clear and maintainable data models using Freezed classes.
- Persist data easily with Isar annotations and collections.
- Perform efficient data operations like fetching, updating, and deleting.
Add Dependencies
1
2
3
4
5
6
7
8
9
10
11
|
isar_version: &isar_version 3.1.0+1 # define the isar version to be used
dependencies:
freezed_annotation: ^2.4.1
isar: *isar_version
isar_flutter_libs: *isar_version
dev_dependencies:
freezed: ^2.4.1
isar_generator: *isar_version
build_runner: any
|
Define Class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:isar/isar.dart';
part 'message.freezed.dart';
part 'message.g.dart';
const modelFreezed = Freezed();
const isarCollection = Collection(ignore: {'props', 'copyWith'});
@modelFreezed
@isarCollection
class Message with _$Message {
const Message._();
const factory Message({
@Index(unique: true) required String id,
required String text,
@Default(MessageStatus.success) MessageStatus status,
// ...
}) = _Message;
Id get isarId => fastHash(id);
@override
@enumerated
MessageStatus get status => super.status;
factory Message.fromJson(Map<String, dynamic> json) =>
_$MessageFromJson(json);
}
enum MessageStatus {
success,
cancel,
timeout,
error;
bool get isSuccess => this == success;
bool get isCancel => this == cancel;
bool get isTimeout => this == timeout;
bool get isError => this == error;
}
/// FNV-1a 64bit hash algorithm optimized for Dart Strings
int fastHash(String string) {
var hash = 0xcbf29ce484222325;
var i = 0;
while (i < string.length) {
final codeUnit = string.codeUnitAt(i++);
hash ^= codeUnit >> 8;
hash *= 0x100000001b3;
hash ^= codeUnit & 0xFF;
hash *= 0x100000001b3;
}
return hash;
}
|
Generate Code
Run the following commands to generate the necessary code:
1
|
flutter pub run build_runner build --delete-conflicting-outputs
|
Enjoy coding 🎉