1.数据库选型
flutter项目,需要使用本地存储,面临三个选择
- shared_preferences
- sqflite
- hive
第一个只能保存key vaule,用起来比较不爽。第二个对桌面版的不支持。
最后选择了hive,用起来还算可以,不过,相对于后台的orm,还是有些东西需要自己处理。
2.项目引用
1 2 3 4 5 6 7 |
dependencies: hive: ^[version] hive_flutter: ^[version] dev_dependencies: hive_generator: ^[version] build_runner: ^[version] |
3.hive的简单使用
之前做个一阵子后台,按照后台的orm逻辑,组装了一下hive。
main.dart里面初始化hive
1 2 3 4 |
void main() async { await InitHive(); runApp(const MyApp()); } |
hive的初始化部分,初始化了三张表
1 2 3 4 5 6 7 8 9 10 11 12 |
import 'package:hive_flutter/adapters.dart'; import 'mclients.dart'; late Box MClients; Future<void> initHive() async { await Hive.initFlutter('data'); Hive.registerAdapter(MClientAdapter()); MClients = await Hive.openBox<MClient>('mclients'); } |
单个表的model
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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
import 'package:flutter/cupertino.dart'; import 'package:hive_flutter/adapters.dart'; import 'hive.dart'; @HiveType(typeId: 1) class MClient { @HiveField(0) String? clientId; @HiveField(1) String? host; @HiveField(2) String? port; @HiveField(3) String? user; @HiveField(4) String? password; MClient({this.clientId, this.host, this.port, this.user, this.password}); } class MClientAdapter extends TypeAdapter<MClient> { @override final typeId = 0; @override MClient read(BinaryReader reader) { return MClient() ..clientId = reader.read() ..host = reader.read() ..password = reader.read() ..user = reader.read() ..password = reader.read(); } @override void write(BinaryWriter writer, MClient obj) { writer.write(obj.clientId); writer.write(obj.host); writer.write(obj.port); writer.write(obj.user); writer.write(obj.password); } } void clientCreate(clientId, host, port, user, password) { var cc = MClient( clientId: clientId, host: host, port: port, user: user, password: password); MClients.put(clientId, cc); } MClient? clientGet(clientId) { if (MClients.get(clientId) != null) { var cc1 = MClients.get(clientId); return cc1; } else { return null; } } List<MClient> clientGetList() { var res = MClients.values.toList(); List<MClient> cc = res.cast<MClient>(); debugPrint("查到list: $cc"); return cc; } void clientDel(clientId) { MClients.delete(clientId); } |
使用model
1 2 3 4 5 6 7 |
late List<String> clientids; getClientids() { clients = ClientGetList(); clientidsd = List.generate(clients.length, (index) => clients[index].clientid); clientids = clientidsd.cast<String>(); } |
结束。