flutter desktop HIVE简单使用
2022-01-22 本文已影响0人
heliping_peter
1.数据库选型
flutter项目,需要使用本地存储,面临三个选择
- shared_preferences
- sqflite
- hive
第一个只能保存key vaule,用起来比较不爽。
第二个对桌面版的不支持。
最后选择了hive,用起来还算可以,不过,相对于后台的orm,还是有些东西需要自己处理。
2.hive的简单使用
之前做个一阵子后台,按照后台的orm逻辑,组装了一下hive。
main.dart里面初始化hive
void main() async {
await InitHive();
runApp(const MyApp());
}
hive的初始化部分,初始化了三张表
late Box MClients;
late Box MsgInfos;
late Box TopicInfos;
Future<void> InitHive() async {
var databasesPath = await getApplicationSupportDirectory();
//Hive.init('./');
print(databasesPath.path);
await Hive.initFlutter(databasesPath.path + '/data');
Hive.registerAdapter(MClientAdapter());
Hive.registerAdapter(MsgInfoAdapter());
Hive.registerAdapter(TopicInfoAdapter());
MClients = await Hive.openBox<MClient>('mclients');
MsgInfos = await Hive.openBox<MsgInfo>('msginfos');
TopicInfos = await Hive.openBox<TopicInfo>('topicinfos');
}
单个表的model
@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>();
print("查到list: $cc");
return cc;
}
void clientDel(clientid) {
MClients.delete(clientid);
}
使用model
late List<String> clientids;
getClientids() {
clients = ClientGetList();
clientidsd =
List.generate(clients.length, (index) => clients[index].clientid);
clientids = clientidsd.cast<String>();
}
结束