我使用 Flutter 开发了演示 web 应用程序并将其上传到我的服务器上,我使用 Hive 数据库 在 Web 应用程序上存储一些数据。
最近我发现当我打开网络应用程序并在其上存储一些数据时, 如果我再次使用不同的浏览器,我将看不到以前存储的数据, 看来 Flutter Web 上的 Hive 会将数据存储在客户端缓存的某个位置。
我现在有3个问题:
hive数据库的位置在哪里,如何手动访问?
如何解决这个问题并使用 Flutter Web 将数据存储在我的服务器上,以便每个用户都可以看到相同的数据?
我应该在服务器端使用 Dart 来实现这个目标吗?如果是,我可以从哪里开始并找到好的文档?
这是我保存和加载数据的代码:
void _initHiveDB() async {
if (_isDBInited) {
return;
}
if(!kIsWeb){
final documentsDirectory = await Path_Provider.getApplicationDocumentsDirectory();
Hive.init(documentsDirectory.path);
}
Hive.registerAdapter(ComplaintModelAdapter(), 0);
_isDBInited = true;
}
Future<bool> saveNewComplaint(ComplaintModel complaintModel)async{
try{
if(_complaintBox==null||!_complaintBox.isOpen){
_complaintBox = await Hive.openBox('Complaints');
}
else{
_complaintBox = Hive.box('Complaints');
}
_complaintBox.add(complaintModel);
return true;
}
catch(exc){
return false;
}
}
Future<List<ComplaintModel>> loadAllComplaints() async {
try{
if(_complaintBox==null||!_complaintBox.isOpen){
_complaintBox = await Hive.openBox('Complaints');
}
else{
_complaintBox = Hive.box('Complaints');
}
//Box<ComplaintModel> complaintBox = await Hive.openBox('Complaints');
//Box<ComplaintModel> complaintBox = await Hive.box('Complaints');
List<ComplaintModel> complaints = _complaintBox.values.toList();
return complaints;
}
catch(exc){
return null;
}}
Hive 正确地完成了它的工作,它是一个嵌入式数据库,对于不同的浏览器必须有不同的数据库。如果您需要在云中共享此信息,您应该寻找其他类型的数据库。云数据库将是解决方案。例如,谷歌工具中有免费的解决方案,或者创建连接到数据库 SQL 的 API。
我理解为什么你会想以这种方式使用 hive,这可能是因为你喜欢它的速度。然而,这只是因为它是嵌入的。如果您希望在仍以嵌入式方式使用它的同时达到该速度,则必须将数据与云或网络数据库同步,以便每个浏览器都可以在后台从云数据库更新其数据,并且客户端浏览器可以获得更新。一个简单的 mysql 数据库就可以了,尽管你必须在 sql 和 nosql 之间来回切换。这是某种去中心化的方法。我之前已经实现过并且效果很好。