我在我的 flutter 应用程序中使用 hive 作为我的 NoSQL 本地数据库。
以下是我的 Hive 课程:
import 'dart:convert';
import 'package:hive/hive.dart';
import 'package:lpa_exam/src/model/listofexams.dart';
import 'package:lpa_exam/src/model/profile.dart';
part 'hiveprofile.g.dart';
@HiveType()
class PersonModel extends HiveObject{
@HiveField(0)
String language;
@HiveField(1)
String examName;
@HiveField(2)
int examId;
@HiveField(3)
Profile profile;
@HiveField(4)
ListExam listexam;
@override
String toString() {
return jsonEncode({
'language': language,
'examName': this.examName,
'examId': examId,
'profile': profile,
'listexam': listexam
});
}
PersonModel(
this.language, this.examName, this.examId, this.profile, this.listexam);
}
Run Code Online (Sandbox Code Playgroud)
所以,我的要求是在每次成功登录时我都应该更新配置文件对象。但为此,我还必须设置所有其他人。
我怎样才能只更新配置文件对象?
代码:
_personBox = Hive.openBox('personBox');
await _personBox.then((item) {
if (!item.isEmpty) {
print('empty');
item.putAt(0, PersonModel(...,..,..,..,...,..)); …Run Code Online (Sandbox Code Playgroud) 我在 main 中初始化了 box 数据库如下
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final appDocumentDirectory = await path_provider.getApplicationDocumentsDirectory();
Hive.init(appDocumentDirectory.path);
Hive.registerAdapter(ContactAdapter());
runApp(MyApp());
}
Run Code Online (Sandbox Code Playgroud)
然后我使用 FutureBuilder 插件在材料应用程序中打开框,如下所示:
FutureBuilder(
future: Hive.openBox<Contact>('contacts'),
builder: (context, snapshot) {
if(snapshot.connectionState == ConnectionState.done){
if(snapshot.hasError){
return Text(snapshot.error.toString() );
}
return ContactPage();
} else {
return Scaffold();
}
}
),
Run Code Online (Sandbox Code Playgroud)
和里面 ContactPage()
我创建了这个:-
ValueListenableBuilder(
valueListenable: Hive.box<Contact>('contacts').listenable(),
builder: (context,Box<Contact> box,_){
if(box.values.isEmpty){
return Text('data is empty');
} else {
return ListView.builder(
itemCount: box.values.length,
itemBuilder: (context,index){
var contact = box.getAt(index);
return ListTile(
title: Text(contact.name),
subtitle: Text(contact.age.toString()), …Run Code Online (Sandbox Code Playgroud) 我正在使用这个包https://pub.dev/packages/hive
我想在配置单元中保存和检索自定义对象的列表。
我尝试过以下方法
await Hive.openBox<List<SourceStations>>(stationBox); //Open box
Box<List<SourceStations>> sourceStationsBox = Hive.box(stationBox);
sourceStationsBox.put(stationBox, listSourceStation); //Saving list of custom object as listSourceStation
//Should probably give lenght of list of custom object
logger.d('station box list length is ${sourceStationsBox.get(stationBox).length}');
Run Code Online (Sandbox Code Playgroud)
但我遇到了以下错误
E/flutter(24061):[错误:flutter/shell/common/shell.cc(199)] Dart错误:未处理的异常:E/flutter(24061):类型“List”不是类型“List”的子类型类型转换 E/flutter (24061): #0 BoxImpl.get (package:hive/src/box/box_impl.dart:43:26) E/flutter (24061): #1
_SourceToDestinationPageState.openStationBox
我已尝试检查此解决方案,但没有足够的想法来解决此问题。
以下是我使用的hive版本
我使用Flutter开发了演示Web应用程序并将其上传到我的服务器上,并使用Hive 数据库在 Web 应用程序上存储一些数据。
最近我发现,当我打开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'); …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用Hiveinside flutter Mobx,在检查用户数据后Hive我切换到另一个屏幕,例如HomeView或Intro
main.dart:
Future<void> main() async {
...
final appDocumentDirectory = await path_provider.getApplicationDocumentsDirectory();
Hive.init(appDocumentDirectory.path);
Hive.registerAdapter(UserAdapter());
_setUpLogging();
runApp(MultiProvider(providers: providers, child: StartupApplication()));
}
Run Code Online (Sandbox Code Playgroud)
StartupApplication类别:我不使用Hive
class StartupApplication extends StatelessWidget {
@override
Widget build(BuildContext context) {
final isPlatformDark = WidgetsBinding.instance.window.platformBrightness == Brightness.dark;
final initTheme = isPlatformDark ? nebrassLightTheme : nebrassLightTheme;
return ThemeProvider(
initTheme: initTheme,
duration: const Duration(milliseconds: 400),
child: Builder(builder: (context) {
return MaterialApp(
title: 'TEST',
theme: ThemeProvider.of(context),
home: const OverlaySupport(child: OKToast( …Run Code Online (Sandbox Code Playgroud) 我有一个单词表。我想将一个单词放入两个不同的框中listview.builder()。
(最喜欢的盒子和学习的盒子)
“HiveError:HiveObject 的同一实例不能存储在两个不同的盒子中。”
我收到这个错误。
有没有办法将数据放入两个不同的盒子中?
如图所示,我希望用户根据自己的要求将一个单词添加到所需的列表中。
我在 Flutter 中使用 Hive 数据库时得到了这个。在下面找出答案
因此,我创建了一个更简单的抽象级别,以便在我的 Flutter 应用程序中使用 Hive。这应该是管理和访问所有配置单元的中心点。由于eggetApplicationDocumentsDirectory在测试期间不可用,我如何才能测试整个文件?
import '../services/workout.dart';
import 'package:hive/hive.dart';
import 'package:path_provider/path_provider.dart' as path_rovider;
import 'workout.dart';
class HiveService {
static final HiveService _singleton = HiveService._internal();
static const String _workoutBox = "workoutBox";
factory HiveService() {
return _singleton;
}
HiveService._internal();
static Future<void> init() async {
final appDocumentDirectory =
await path_rovider.getApplicationDocumentsDirectory();
Hive.init(appDocumentDirectory.path);
Hive.registerAdapter(WorkoutAdapter());
}
static Future openWorkouts() {
return Hive.openBox<Workout>(_workoutBox);
}
static Future close() {
return Hive.close();
}
}
Run Code Online (Sandbox Code Playgroud) 我将列表保存到 Hive Box 中的索引中。
class Person {
String name;
Person(this.name);
}
List<Person> friends = [];
friends.add(Person('Jerry'));
var accountBox = Hive.openBox('account');
accountBox.put('friends',friends);
//Testing as soon as saved to make sure it's storing correctly.
List<Person> friends = accountBox.get('friends');
assert(friends.length == 1);
Run Code Online (Sandbox Code Playgroud)
所以这一切都按预期进行。由于某些疯狂的原因,当我热重启应用程序并尝试从 Hive 获取好友列表时,它不再返回List<Person>. 它返回一个List<dynamic>
var accountBox = Hive.openBox('account');
List<Person> friends = accountBox.get('friends');
///ERROR
E/flutter (31497): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled
Exception: type 'List<dynamic>' is not a subtype of type 'List<Person>'
E/flutter (31497): <asynchronous suspension>
etc...
Run Code Online (Sandbox Code Playgroud)
可能是什么原因造成的?这太不寻常了。
使用 Hive 缓存 API 结果的正确方法是什么?
目前我计划实现的方式是使用请求 URL 作为 key,使用返回的数据作为 body。
有没有适当的方法可以使生产更加友好?我找不到教程,因为大多数教程都是通过使用另一个包来抽象的,该包可以为他们处理这个问题,或者教程使用不同的包。