Freezed 是一个代码生成器,可帮助您在 Dart 中创建不可变、可序列化的类,减少重复代码,并提高代码可读性和可维护性。
Isar 是适用于 Flutter 的速度极快、易于使用且完全异步的 NoSQL 数据库。
Freezed 和 Isar 结合起来可让您:
- 使用 Freezed 类定义清晰且可维护的数据模型。
- 使用 Isar 轻松持久化数据。
- 执行高效的数据操作,例如获取、更新和删除。
添加依赖项
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
|
定义 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;
}
|
生成代码
运行以下命令来生成代码:
1
|
flutter pub run build_runner build --delete-conflicting-outputs
|
享受编码吧 🎉