我在我的 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版本
我使用 Hive 和 Flutter 来存储密钥为字母数字字符串的联系人,每个联系人数据都是一个带有时间戳的地图
框行=
Key. => Value
'abc123' => {'name': 'JK', 'country':'GB', 'timestamp': '568'},
'etergb' => {'name': 'FS', 'country':'DE', 'timestamp': '425'}
'546hfg' => {'name': 'TD', 'country':'GB', 'timestamp': '687'}
Run Code Online (Sandbox Code Playgroud)
现在可以使用where country=GB条件过滤这些并按 map.item.timestamp ASC/DESC 对行进行排序
我不太清楚如何在 Flutter 中使用 Hive DB。我的意思是我有一个“WooCustomer”模型类,我想将其存储在本地(一旦客户登录)。
我的问题是,我是否必须将其转换WooCustomer然后HiveObject创建TypeAdapter,还是TypeAdapter<WooCustomer>直接创建?
PS:WooCustomer 是一个外部 pkg。
这是正确的实施方法吗TypeAdapter<WooCustomer>?
class DatabaseAdapterService extends TypeAdapter<WooCustomer> {
@override
final int typeId = 0;
@override
WooCustomer read(BinaryReader reader) {
return WooCustomer()
..id = reader.read()
..username = reader.read()
..firstName = reader.read()
..lastName = reader.read()
..email = reader.read()
..password = reader.read()
..avatarUrl = reader.read()
..role = reader.read()
..dateCreated = reader.read()
..dateCreatedGmt = reader.read()
..dateModified = reader.read()
..dateModifiedGmt = reader.read()
..isPayingCustomer = reader.read()
..links = reader.read() …Run Code Online (Sandbox Code Playgroud) 当我尝试将相同的值保存在(多个)不同的框中时,我遇到了问题。
这是配置单元的输出:
[VERBOSE-2:ui_dart_state.cc(199)] Unhandled Exception: HiveError: The same instance of
an HiveObject cannot be stored in two different boxes.
Run Code Online (Sandbox Code Playgroud)
我真的很感激,如果有人能告诉我,如何将同一个对象保存在多个框中(默认情况下这样做)?
这里是 Riverpod 的新手。(使用 Flutter 和 hooks_riverpod,顺便说一句)。
使用 Hive 存储相关的项目列表。我需要调用Hive.initFlutter并等待 Hive 初始化,并在我的应用程序加载时执行相同的操作来打开配置单元框。之后,对 Hive 的调用是同步的。
我最初的想法(尽管我愿意接受更好的想法)是创建一个包含两个列表的 StateNotifier。该通知程序可以有一个异步的 setUp 函数。简化后的样子如下:
class ItemsNotifier extends StateNotifier<ItemsState> {
ItemsNotifier() : super(ItemsState([], []));
setUp() async {
await Hive.initFlutter();
// What is ItemDao? It's a data accessor object singleton used to house Hive logic.
await ItemDao().openBoxes();
// Putting a breakpoint here, I can see by calling `ItemDao().list1` etc that the lists have loaded with items as expected, but setting state here does not trigger a rebuild …Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个尝试 Hive 数据库并面临一些我无法解决的问题。
我的模型是
@HiveType(typeId: 1)
class Tasks {
@HiveField(0)
final String task;
@HiveField(1)
final bool isCompleted;
Tasks({required this.task, required this.isCompleted});
}
Run Code Online (Sandbox Code Playgroud)
以及 hive_generator 生成的文件
class TasksAdapter extends TypeAdapter<Tasks> {
@override
final int typeId = 1;
@override
Tasks read(BinaryReader reader) {
final numOfFields = reader.readByte();
final fields = <int, dynamic>{
for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
};
return Tasks(
task: fields[0] as String,
isCompleted: fields[1] as bool,
);
}
@override
void write(BinaryWriter writer, Tasks obj) …Run Code Online (Sandbox Code Playgroud) 我正在开发一个从 firebase 云消息传递接收通知的应用程序。我收到消息后将其保存在 Hive 中。我有一个通知屏幕,显示从配置单元读取的通知,该通知在收到通知时立即更新。这一直运作良好。
现在的问题是,应用程序在后台运行时收到的通知(不是终止/终止)保存在配置单元中,但导航到通知屏幕时屏幕不会更新(看不到配置单元中的更新),直到应用程序终止并且重新运行。
我读到这是因为 onBackgroundMessage 处理程序在不同的隔离上运行,并且隔离无法共享存储。看来我需要一种方法将 Hive 通知更新从 onBackgroundMessage 处理程序传递到主隔离。
这是我到目前为止的实现
push_message.dart 实例保存在hive中的通知类
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:app_name/helpers/helpers.dart';
part 'push_message.g.dart';
@HiveType(typeId: 1)
class PushMessage extends HiveObject {
@HiveField(0)
int id = int.parse(generateRandomNumber(7));
@HiveField(1)
String? messageId;
@HiveField(2)
String title;
@HiveField(3)
String body;
@HiveField(4)
String? bigPicture;
@HiveField(5)
DateTime? sentAt;
@HiveField(6)
DateTime? receivedAt;
@HiveField(7)
String? payload;
@HiveField(8, defaultValue: '')
String channelId = 'channel_id';
@HiveField(9, defaultValue: 'channel name')
String channelName …Run Code Online (Sandbox Code Playgroud) dart dart-isolates flutter firebase-cloud-messaging flutter-hive
我有一个单词表。我想将一个单词放入两个不同的框中listview.builder()。
(最喜欢的盒子和学习的盒子)
“HiveError:HiveObject 的同一实例不能存储在两个不同的盒子中。”
我收到这个错误。
有没有办法将数据放入两个不同的盒子中?
如图所示,我希望用户根据自己的要求将一个单词添加到所需的列表中。