isar / hive Goto Github PK
View Code? Open in Web Editor NEWLightweight and blazing fast key-value database written in pure Dart.
License: Apache License 2.0
Lightweight and blazing fast key-value database written in pure Dart.
License: Apache License 2.0
Although I have annotations, I haven't used hive_generator
, because documentation is missing? I've found some information online about running build_runner
which mentions some entry.g.dart
file while it runs, but doesn't generate it? So I've written the adapter manually.
Steps to Reproduce
put() a list of entries
openBox() that has entries
Receive RangeError:
E/flutter (31284): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: RangeError: Not enough bytes available.
E/flutter (31284): #0 BinaryReaderImpl._requireBytes (package:hive/src/binary/binary_reader_impl.dart:40)
E/flutter (31284): #1 BinaryReaderImpl.readByte (package:hive/src/binary/binary_reader_impl.dart:52)
E/flutter (31284): #2 BinaryReaderImpl.read (package:hive/src/binary/binary_reader_impl.dart:211)
E/flutter (31284): #3 BinaryReaderImpl.readList (package:hive/src/binary/binary_reader_impl.dart:192)
E/flutter (31284): #4 BinaryReaderImpl.read (package:hive/src/binary/binary_reader_impl.dart:236)
E/flutter (31284): #5 Frame.decodeValue (package:hive/src/binary/frame.dart:89)
E/flutter (31284): #6 Frame.decode (package:hive/src/binary/frame.dart:78)
E/flutter (31284): #7 FrameIoHelper.framesFromFile (package:hive/src/io/frame_io_helper.dart:77)
E/flutter (31284): <asynchronous suspension>
E/flutter (31284): #8 StorageBackendVm.initialize (package:hive/src/backend/storage_backend_vm.dart:85)
E/flutter (31284): <asynchronous suspension>
E/flutter (31284): #9 BoxBase.initialize (package:hive/src/box/box_base.dart:87)
E/flutter (31284): #10 HiveImpl.openBoxInternal (package:hive/src/hive_impl.dart:92)
E/flutter (31284): <asynchronous suspension>
E/flutter (31284): #11 HiveImpl.openBox (package:hive/src/hive_impl.dart:72)
E/flutter (31284): <asynchronous suspension>
E/flutter (31284): #12 openBox.<anonymous closure>
Code sample
@HiveType()
class Entry {
@HiveField(0)
String title;
@HiveField(1)
String url;
@HiveField(2)
Entry next;
@HiveField(3)
List<Entry> children = List();
Entry(this.title, this.url);
static initializeHive() {
Hive.registerAdapter(EntryAdapter(), 0);
}
get urlExists => url != null && url.isNotEmpty;
}
class EntryAdapter extends TypeAdapter<Entry> {
@override
Entry read(BinaryReader reader) {
Entry e;
try {
String title = reader.readString();
String url = reader.readString();
e = Entry(title, url);
bool isNext = reader.readBool();
if (isNext) {
Entry x = read(reader);
if (x != null) {
e.next = x;
}
}
var length = reader.readUint32();
for (var i = 0; i < length; ++i) {
bool b = reader.readBool();
if (b) {
Entry x = read(reader);
if (x != null) {
e.children.add(x);
}
}
}
return e;
} catch (exception) {
return null;
}
}
@override
void write(BinaryWriter writer, Entry e) {
if (e == null || !e.urlExists) {
return;
}
writer.writeString(e.title);
writer.writeString(e.url);
if (e.next == null || !e.urlExists) {
writer.writeBool(false);
} else {
writer.writeBool(true);
write(writer, e.next);
}
writer.writeUint32(e.children.length);
for (var child in e.children) {
if (child == null || !child.urlExists) {
writer.writeBool(false);
} else {
writer.writeBool(true);
write(writer, child);
}
}
}
}
**Version**
- Platform: Android
- Flutter version: 1.10.7-pre.99
- Hive version: 1.0.0
Thank you for the great work. Can Hive be used for state management? What will be the disadvantages? Is it an anti-pattern? Is there anyone who tried?
Request for ReadOnly Box which can read data without write permission(Ex.from flutter assets)
It would be great if Box
support generic types such as Box<K, V>
.
Question
Hi, I have a question related to how to use the hive package.
Btw, I like it a lot and I'm definitely planning on using it in my projects.
I have a scenario where I need to synchronize some data from server, but I don't want to let the user wait until the sync finishes.
Also, some stuff can be written/read to/from the box even if the sync did not finished. So I tried to simulate this scenario in a very "stupid way":
Code sample
Future<void> Write1() async {
final now = DateTime.now();
final box = Hive.box("test");
for (int i = 0; i < 10000; i++) {
await box.put(i.toString(), i.toString());
}
print("Finished 1 after ${DateTime.now().difference(now).inMilliseconds}");
}
Future<void> Write2() async {
final now = DateTime.now();
final box = Hive.box("test");
for (int i = 10001; i < 20000; i++) {
await box.put(i.toString(), i.toString());
}
print("Finished 2 after ${DateTime.now().difference(now).inMilliseconds}");
}
test() async {
final box = await Hive.openBox("test");
unawaited(Write1());
unawaited(Write2());
await Future.delayed(Duration(milliseconds: 300));
print("Getting value from box: ${box.get("100")}");
}
In the first run, the code almost always runs with success. But if I restart the app, in 90% of the cases I get the exception below.
Am I using your library in a wrong way?
E/flutter ( 4637): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: Bad state: No element
E/flutter ( 4637): #0 ListQueue.removeFirst (dart:collection/queue.dart:729:25)
E/flutter ( 4637): #1 Keystore.cancelTransaction (package:hive/src/box/keystore.dart:143:33)
E/flutter ( 4637): #2 BoxImpl._writeFrame (package:hive/src/box/box_impl.dart:74:16)
E/flutter ( 4637): <asynchronous suspension>
E/flutter ( 4637): #3 BoxImpl.put (package:hive/src/box/box_impl.dart:57:12)
E/flutter ( 4637): #4 GlobalApplicationState.Write2 (package:eatntrack/features/shared/presentation/models/global_application_state.dart:56:17)
E/flutter ( 4637): <asynchronous suspension>
E/flutter ( 4637): #5 GlobalApplicationState._initialize (package:eatntrack/features/shared/presentation/models/global_application_state.dart:67:15)
E/flutter ( 4637): #6 _asyncThenWrapperHelper.<anonymous closure> (dart:async-patch/async_patch.dart:71:64)
E/flutter ( 4637): #7 _rootRunUnary (dart:async/zone.dart:1132:38)
E/flutter ( 4637): #8 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
E/flutter ( 4637): #9 _FutureListener.handleValue (dart:async/future_impl.dart:137:18)
E/flutter ( 4637): #10 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:678:45)
E/flutter ( 4637): #11 Future._propagateToListeners (dart:async/future_impl.dart:707:32)
E/flutter ( 4637): #12 Future._completeWithValue (dart:async/future_impl.dart:522:5)
E/flutter ( 4637): #13 _AsyncAwaitCompleter.complete (dart:async-patch/async_patch.dart:30:15)
E/flutter ( 4637): #14 _completeOnAsyncReturn (dart:async-patch/async_patch.dart:288:13)
E/flutter ( 4637): #15 HiveImpl.openBox (package:hive/src/hive_impl.dart)
E/flutter ( 4637): #16 _asyncThenWrapperHelper.<anonymous closure> (dart:async-patch/async_patch.dart:71:64)
E/flutter ( 4637): #17 _rootRunUnary (dart:async/zone.dart:1132:38)
E/flutter ( 4637): #18 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
E/flutter ( 4637): #19 _FutureListener.handleValue (dart:async/future_impl.dart:137:18)
E/flutter ( 4637): #20 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:678:45)
E/flutter ( 4637): #21 Future._propagateToListeners (dart:async/future_impl.dart:707:32)
E/flutter ( 4637): #22 Future._completeWithValue (dart:async/future_impl.dart:522:5)
E/flutter ( 4637): #23 _AsyncAwaitCompleter.complete (dart:async-patch/async_patch.dart:30:15)
E/flutter ( 4637): #24 _completeOnAsyncReturn (dart:async-patch/async_patch.dart:288:13)
E/flutter ( 4637): #25 HiveImpl.openBoxInternal (package:hive/src/hive_impl.dart)
E/flutter ( 4637): #26 _asyncThenWrapperHelper.<anonymous closure> (dart:async-patch/async_patch.dart:71:64)
E/flutter ( 4637): #27 _rootRunUnary (dart:async/zone.dart:1132:38)
E/flutter ( 4637): #28 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
E/flutter ( 4637): #29 _FutureListener.handleValue (dart:async/future_impl.dart:137:18)
E/flutter ( 4637): #30 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:678:45)
E/flutter ( 4637): #31 Future._propagateToListeners (dart:async/future_impl.dart:707:32)
E/flutter ( 4637): #32 Future._completeWithValue (dart:async/future_impl.dart:522:5)
E/flutter ( 4637): #33 _AsyncAwaitCompleter.complete (dart:async-patch/async_patch.dart:30:15)
E/flutter ( 4637): #34 _completeOnAsyncReturn (dart:async-patch/async_patch.dart:288:13)
E/flutter ( 4637): #35 StorageBackendVm.initialize (package:hive/src/backend/storage_backend_vm.dart)
E/flutter ( 4637): #36 _asyncThenWrapperHelper.<anonymous closure> (dart:async-patch/async_patch.dart:71:64)
E/flutter ( 4637): #37 _rootRunUnary (dart:async/zone.dart:1132:38)
E/flutter ( 4637): #38 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
E/flutter ( 4637): #39 _FutureListener.handleValue (dart:async/future_impl.dart:137:18)
E/flutter ( 4637): #40 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:678:45)
E/flutter ( 4637): #41 Future._propagateToListeners (dart:async/future_impl.dart:707:32)
E/flutter ( 4637): #42 Future._completeWithValue (dart:async/future_impl.dart:522:5)
E/flutter ( 4637): #43 _AsyncAwaitCompleter.complete (dart:async-patch/async_patch.dart:30:15)
E/flutter ( 4637): #44 _completeOnAsyncReturn (dart:async-patch/async_patch.dart:288:13)
E/flutter ( 4637): #45 Lock.synchronized (package:hive/src/util/lock.dart)
E/flutter ( 4637): #46 _asyncThenWrapperHelper.<anonymous closure> (dart:async-patch/async_patch.dart:71:64)
E/flutter ( 4637): #47 _rootRunUnary (dart:async/zone.dart:1132:38)
E/flutter ( 4637): #48 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
E/flutter ( 4637): #49 _FutureListener.handleValue (dart:async/future_impl.dart:137:18)
E/flutter ( 4637): #50 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:678:45)
Version
When creating a new box, like so: var box = await Hive.box('SettingsBox');
is box
null until a value has been put into the box?
Hi,
Put it into own repository and organisation.
I made it with my project too, ezored (https://ezored.com).
Thanks.
Steps to Reproduce
When run $ flutter pub run build_runner build
in project with hive
i getting error:
[INFO] Generating build script...
[INFO] Generating build script completed, took 287ms
[WARNING] Deleted previous snapshot due to missing asset graph.
[INFO] Creating build script snapshot......
[INFO] Creating build script snapshot... completed, took 10.4s
[INFO] Initializing inputs
[INFO] Building new asset graph...
[INFO] Building new asset graph completed, took 780ms
[INFO] Checking for unexpected pre-existing outputs....
[INFO] Deleting 1 declared outputs which already existed on disk.
[INFO] Checking for unexpected pre-existing outputs. completed, took 2ms
[INFO] Running build...
[SEVERE] hive_generator:hive_generator on test/module_digest_test.dart:
Invalid argument(s): Path must be absolute : dart:core
[SEVERE] hive_generator:hive_generator on lib/src/bloc/digest/digest_event.dart:
Invalid argument(s): Path must be absolute : dart:core
[SEVERE] hive_generator:hive_generator on lib/src/bloc/digest/digest_state.dart:
Invalid argument(s): Path must be absolute : dart:core
[SEVERE] hive_generator:hive_generator on lib/src/bloc/digest_detail/digest_detail_state.dart:
Invalid argument(s): Path must be absolute : dart:core
[SEVERE] hive_generator:hive_generator on lib/src/bloc/digest_detail/digest_detail_event.dart:
Invalid argument(s): Path must be absolute : dart:core
[SEVERE] hive_generator:hive_generator on lib/src/data/models/responses/digest_detail.dart:
Invalid argument(s): Path must be absolute : dart:core
[SEVERE] hive_generator:hive_generator on lib/src/data/models/responses/digest.dart:
Invalid argument(s): Path must be absolute : dart:core
You have hit a bug in build_runner
Please file an issue with reproduction steps at https://github.com/dart-lang/build/issues
NoSuchMethodError: The getter 'references' was called on null.
Receiver: null
Tried calling: references
dart:core Object.noSuchMethod
package:analyzer/src/summary2/linked_bundle_context.dart 22:47 new LinkedBundleContext
package:analyzer/src/dart/analysis/library_context.dart 407:11 LibraryContext._createElementFactory
package:analyzer/src/dart/analysis/library_context.dart 94:7 new LibraryContext
package:analyzer/src/dart/analysis/driver.dart 1439:29 AnalysisDriver._createLibraryContext
package:analyzer/src/dart/analysis/driver.dart 1380:28 AnalysisDriver._computeUnitElement.<fn>
package:analyzer/src/dart/analysis/performance_logger.dart 34:15 PerformanceLog.run
package:analyzer/src/dart/analysis/driver.dart 1378:20 AnalysisDriver._computeUnitElement
package:analyzer/src/dart/analysis/driver.dart 997:34 AnalysisDriver.performWork
package:analyzer/src/dart/analysis/driver.dart 1931:24 AnalysisDriverScheduler._run
package:analyzer/src/dart/analysis/driver.dart 1865:5 AnalysisDriverScheduler.start
package:build_resolvers/src/analysis_driver.dart 54:13 analysisDriver
package:build_resolvers/src/resolver.dart 138:18 new AnalyzerResolvers
package:build_runner_core/src/generate/options.dart 192:19 BuildOptions.create
package:build_runner/src/generate/build.dart 85:36 build
package:build_runner/src/entrypoint/build.dart 28:24 BuildCommand.run
package:args/command_runner.dart 197:27 CommandRunner.runCommand
package:args/command_runner.dart 112:25 CommandRunner.run.<fn>
dart:async new Future.sync
package:args/command_runner.dart 112:14 CommandRunner.run
package:build_runner/src/entrypoint/run.dart 24:31 run
.dart_tool\build\entrypoint\build.dart 22:22 main
Code sample
import 'package:hive/hive.dart';
part 'digest_cache.g.dart';
@HiveType()
class DigestCache {
DigestCache({
this.readingProgress,
this.updateDate,
});
@HiveField(0)
int readingProgress;
@HiveField(1)
DateTime updateDate;
}
Version
hello!
sorry for asking you for help instead of reporting an issue, but i don't know what to do now 😅
yesterday i was trying hive in a TODO list app, and for each note i need to generate a unique key
i've used UUID to generate a random key, but i faced an error of invalid arguments, problably i was doing something wrong. So, do you recommend any package or any method to generate a random key for each note ?
It's a pain to copy assets files to the app directory before opening them with Hive.
Is there anyways to load using an asset path directly?
I'm happy to implement in a PR if you have a solution in mind.
Hi,
Hive is great, and I wanna use it in a mobile-first offline-first app. So I have to sync data with my back-end server silently.
My app will encrypt user data and since Hive already does it, the best way is sync the encrypted string(or what ever binary format) to the server. So I need a method to get this encrypted string.
Maybe additional methods like Future<void> putRaw(String k, String v)
and Future<String> getRaw(String k)
are good choice?
Hi,
I thought I give hive a try. It worked well when I only stored one short string; But after storing a longer JSON String I get this exeption in line 144 of your frame.dart.
The string in questions is 1665544 characters long.
Btw: I tried first to store the map without converting to json, but when readin back I only got one long string.
I hope you can fix this.
Cheers
Thomas
I got this error after some time when calling put
Unhandled Exception: RangeError: Value not in range
Stacktrace as follows (trace from the app prior to the hive related trace is not included)
flutter: .. products fetched from the api.
[VERBOSE-2:ui_dart_state.cc(148)] Unhandled Exception: RangeError: Value not in range: -674520
#0 _rangeCheck (dart:typed_data-patch/typed_data_patch.dart:4442:5)
#1 _ByteBuffer.asUint8List (dart:typed_data-patch/typed_data_patch.dart:1923:5)
#2 new Uint8List.view (dart:typed_data:820:19)
#3 BufferedFileReader.read
package:hive/…/io/buffered_file_reader.dart:47
<asynchronous suspension>
#4 StorageBackendVm.compact.<anonymous closure>.<anonymous closure>
package:hive/…/backend/storage_backend_vm.dart:186
<asynchronous suspension>
#5 Lock.synchronized
package:hive/…/util/lock.dart:18
<asynchronous suspension>
#6 StorageBackendVm.compact.<anonymous closure>
package:hive/…/backend/storage_backend_vm.dart:174
#7 Lock.synchronized
package:hive/…/util/lock.dart:18
<asynchronous suspension>
#8 StorageBackendVm.compact
package:hive/…/backend/storage_backend_vm.dart:173
<asynchronous suspension>
#9 BoxImpl.compact (pack<…>
Error calling sqlite3_step (1: cannot rollback - no transaction is active) SQLITE_ERROR
DB Query: ROLLBACK
Unknown error finalizing or resetting statement (1: cannot rollback - no transaction is active)
DB Query: ROLLBACK
For context, I'm trying to put a big amount of data into the box (like a list of 100 Map<String, dynamic>
with detailed attributes.
It might be the cause of the exception but the exception should state that. Initially, the IDE (VSCode) pauses for an exception but I can't see any stacktrace and the offending line is not presented. I was able to see the exception when I unticked Uncaught Exceptions
In my app, I have some immutable data class, like the following:
@immutable
@HiveType()
class SampleClass {
@HiveField(0)
final String someAttribute;
@HiveField(1)
final String otherAttribute;
SampleClass({
@required this.someAttribute,
@required this.otherAttribute,
}) : assert(someAttribute != null),
assert(otherAttribute != null);
}
However, Hive currently cannot generate valid code for final fields because it relies on setting the attributes after creating the object (as it doesn't know about the constructor).
Is there a way final attributes could possibly be supported in the future?
Is there more info on the binary format ?
I am working in golang and protobufs. So i am thinking about writing a code generator to work with hive to help code gen from the Server IDL
Stacktrace
Unhandled Exception: Bad state: No element
#0 ListQueue.removeFirst (dart:collection/queue.dart:729:25)
#1 Keystore.cancelTransaction (package:hive/src/box/keystore.dart:143:33)
#2 BoxImpl._writeFrame (package:hive/src/box/box_impl.dart:74:16)
<asynchronous suspension>
#3 BoxImpl.put (package:hive/src/box/box_impl.dart:57:12)
#4 Cache.setLastFetched (package:tavern/src/cache.dart:48:11)
#5 Cache.[]= (package:tavern/src/cache.dart:93:5)
#6 MapMixin.addAll (dart:collection/maps.dart:122:11)
#7 PageRepository.get (package:tavern/screens/home/home_bloc.dart:169:21)
#8 _asyncThenWrapperHelper.<anonymous closure> (dart:async-patch/async_patch.dart:71:64)
#9 _rootRunUnary (dart:async/zone.dart:1132:38)
#10 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
#11 _FutureListener.handleValue (dart:async/future_impl.dart:137:18)
#12 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:678:45)<…>
Steps to Reproduce
Not sure how. It only happens when the app starts, a box is opened and written to quickly. If I put a breakpoint and it pauses, then when it resumes, the error doesn't show up
Code sample
link to repo: https://github.com/ThinkDigitalSoftware/tavern
Image of the frame, just in case you can grab something from it
Version
Flutter 1.10.1 • channel dev • https://github.com/flutter/flutter.git
Framework • revision ce45c2d3e6 (8 days ago) • 2019-09-06 20:11:41 -0400
Engine • revision b9ce2500d9
Tools • Dart 2.5.0 (build 2.5.0-dev.4.0 be66176534)
Hive version: 1.0.0
I know Hive isn't ready for production apps, but in my case I'm planning to use the library for caching purposes, so if the data is lost it isn't a big deal.
As I have seen breaking changes in the binary format, I would like to know how Hive manages these changes from version to version. Is the data just removed? Is there anything I should take into account?
In the example, if I want to register a class to a HiveType, I'd have to put @HiveField(n)
to the fields that I want to store, right?
@HiveType()
class Dog {
@HiveField(0)
String name;
@HiveField(1)
int age;
@HiveField(2)
List<Person> friends;
}
What if I have another class that I want to store, like Cat
?
@HiveType()
class Cat {
@HiveField(3)
String name;
@HiveField(4)
int age;
@HiveField(5)
List<Person> friends;
}
should the numbering continue, or it goes back to zero?
Question
Is anyone able to build their app with hive support to build for web? I'm not even able to build the sample todo app .
Version
I have a tasks model annotated with hive.
import 'package:hive/hive.dart';
part 'task.g.dart';
@HiveType()
class Task {
@HiveField(0)
String title;
@HiveField(1)
bool done;
@HiveField(2)
int id;
Task({this.title, this.done});
}
Here is the repo that handles these tasks files
class TasksRepo {
static const _TASKS_KEY = "tasks";
List<Task> tasks;
Box tasksBox;
final Function() rebuildWidget;
TasksRepo({this.rebuildWidget});
openTasksBox() async {
tasksBox = await Hive.box('tasksBox');
tasksBox.watch().listen((e) {
rebuildWidget();
});
}
getTasks() async {
if (tasksBox == null) {
await openTasksBox();
}
tasks = await tasksBox.get(_TASKS_KEY, defaultValue: [
Task(title: "Create new Task", done: false),
Task(title: "Do that task", done: false),
Task(title: "Mark task as Done", done: true),
]);
return tasks;
}
void closeBox() async {
await tasksBox.close();
}
void toggleTaskDone(Task task) async {
tasks = await getTasks();
var index = tasks.indexWhere((t) => t.title == task.title);
task.done = !task.done;
tasks[index] = task;
tasksBox.put(_TASKS_KEY, tasks);
}
clearCompleted() async {
tasks = await getTasks();
tasks.removeWhere((task) => task.done);
tasksBox.put(_TASKS_KEY, tasks);
}
void addTask(String title) async {
tasks = await getTasks();
tasks.insert(0, Task(done: false, title: title));
tasksBox.put(_TASKS_KEY, tasks);
}
}
On the first launch of the application, everything works as expected I can add tasks and clear them. But on the second launch, the application throws this error.
I/flutter ( 6440):
E/flutter ( 6440): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: RangeError: Not enough bytes available.
E/flutter ( 6440): #0 BinaryReaderImpl._requireBytes (package:hive/src/binary/binary_reader_impl.dart:31)
E/flutter ( 6440): #1 BinaryReaderImpl.viewBytes (package:hive/src/binary/binary_reader_impl.dart:49)
E/flutter ( 6440): #2 BinaryReaderImpl.readString (package:hive/src/binary/binary_reader_impl.dart:102)
E/flutter ( 6440): #3 TaskAdapter.read (package:lessphone/app/tasks/task.g.dart:16)
E/flutter ( 6440): #4 BinaryReaderImpl.read (package:hive/src/binary/binary_reader_impl.dart:228)
E/flutter ( 6440): #5 BinaryReaderImpl.readList (package:hive/src/binary/binary_reader_impl.dart:175)
E/flutter ( 6440): #6 BinaryReaderImpl.read (package:hive/src/binary/binary_reader_impl.dart:219)
E/flutter ( 6440): #7 Frame.decodeBody (package:hive/src/binary/frame.dart:119)
E/flutter ( 6440): #8 readFramesFromFile (package:hive/src/io/frame_io_helper.dart:67)
E/flutter ( 6440): <asynchronous suspension>
E/flutter ( 6440): #9 StorageBackendVm.initialize (package:hive/src/backend/storage_backend_vm.dart:87)
E/flutter ( 6440): <asynchronous suspension>
E/flutter ( 6440): #10 BoxImpl.initialize (package:hive/src/box/box_impl.dart:88)
E/flutter ( 6440): <asynchronous suspension>
E/flutter ( 6440): #11 openBox (package:hive/src/backend/storage_backend_vm.dart:32)
E/flutter ( 6440): <asynchronous suspension>
E/flutter ( 6440): #12 HiveImpl.box (package:hive/src/hive_impl.dart:50)
E/flutter ( 6440): <asynchronous suspension>
E/flutter ( 6440): #13 TasksRepo.openTasksBox (package:lessphone/app/tasks/tasks_repo.dart:15)
E/flutter ( 6440): <asynchronous suspension>
E/flutter ( 6440): #14 TasksRepo.getTasks (package:lessphone/app/tasks/tasks_repo.dart:23)
E/flutter ( 6440): <asynchronous suspension>
E/flutter ( 6440): #15 TasksRepo.addTask (package:lessphone/app/tasks/tasks_repo.dart:52)
E/flutter ( 6440): <asynchronous suspension>
E/flutter ( 6440): #16 _TasksScreenState.build.<anonymous closure>.<anonymous closure> (package:lessphone/app/ui/tasks_screen.dart:56)
E/flutter ( 6440): #17 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:635)
E/flutter ( 6440): #18 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:711)
E/flutter ( 6440): #19 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182)
E/flutter ( 6440): #20 TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:365)
E/flutter ( 6440): #21 TapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:312)
E/flutter ( 6440): #22 GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:156)
E/flutter ( 6440): #23 _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:222)
E/flutter ( 6440): #24 _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:198)
E/flutter ( 6440): #25 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156)
E/flutter ( 6440): #26 _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102)
E/flutter ( 6440): #27 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86)
E/flutter ( 6440): #28 _rootRunUnary (dart:async/zone.dart:1136)
E/flutter ( 6440): #29 _CustomZone.runUnary (dart:async/zone.dart:1029)
E/flutter ( 6440): #30 _CustomZone.runUnaryGuarded (dart:async/zone.dart:931)
E/flutter ( 6440): #31 _invoke1 (dart:ui/hooks.dart:250)
E/flutter ( 6440): #32 _dispatchPointerDataPacket (dart:ui/hooks.dart:159)
E/flutter ( 6440):
Hi, Now I'm getting this error when calling await Hive.openBox(name);
Dunno how it happened it was working earlier. I stopped the app and launched it again (not just a Hot Restart) and then I got this.
Hello,
i've red the examples and docs, and it seems that you alwals initialize hive when app starts.
Is there a way to know if it were already initialized?
Or it is not necessary?
This way you can have a widget update when the value of a certain key updates!
Is your feature request related to a problem? Please describe.
Currently, if I have a generic type, I can't register a generic TypeAdapter for that type.
For example, I have the following class (coming from the repository package):
class Id<T> {
String id;
... (custom implementations of ==, hashCode etc.)
String toString() => '<$T with id $id>';
}
It's then used by my entity classes like this:
@HiveType()
class Article {
@HiveField(0)
Id<Article> id;
@HiveField(1)
...
}
Now, I want to save an Article
to hive.
I registered the automatically generated ArticleAdapter()
and a custom-built Adapter<Id>
.
However, hive complains that it doesn't know how to serialize Id<Article>
. That's because internally, there's a map of types to their adapters and Id != Id<Article>
.
Can this easily be implemented?
Steps to Reproduce
When trying to generate a TypeAdapter with a Uint8list inside it throws the following error.
$ flutter packages pub run build_runner build --delete-conflicting-outputs -v
Error running TypeAdapterGenerator
RangeError (index): Invalid value: Valid value range is empty: 0
dart:core List.[]
package:hive_generator/src/class_builder.dart 86:38 ClassBuilder._castIterable
package:hive_generator/src/class_builder.dart 69:36 ClassBuilder._cast
package:hive_generator/src/class_builder.dart 59:34 ClassBuilder.buildRead
package:hive_generator/src/type_adapter_generator.dart 24:19 TypeAdapterGenerator.generateForAnnotatedElement
package:source_gen/src/generator_for_annotation.dart 47:30 GeneratorForAnnotation.generate
package:source_gen/src/builder.dart 280:35 _generate
package:source_gen/src/builder.dart 73:15 _Builder._generateForLibrary
package:source_gen/src/builder.dart 67:11 _Builder.build
package:build runBuilder
package:build_runner_core/src/generate/build_impl.dart 477:19 _SingleBuild._runForInput.<fn>.<fn>.<fn>
package:build_runner_core/src/generate/performance_tracker.dart 300:15 _NoOpBuilderActionTracker.trackStage
package:build_runner_core/src/generate/build_impl.dart 475:23 _SingleBuild._runForInput.<fn>.<fn>
package:timing/src/timing.dart 222:44 NoOpTimeTracker.track
package:build_runner_core/src/generate/build_impl.dart 434:22 _SingleBuild._runForInput.<fn>
package:pool/pool.dart 127:28 Pool.withResource
package:build_runner_core/src/generate/build_impl.dart 430:17 _SingleBuild._runForInput
package:build_runner_core/src/generate/build_impl.dart 378:38 _SingleBuild._runBuilder.<fn>
dart:async Future.wait
package:build_runner_core/src/generate/build_impl.dart 377:36 _SingleBuild._runBuilder
dart:async _AsyncAwaitCompleter.start
package:build_runner_core/src/generate/build_impl.dart 375:40 _SingleBuild._runBuilder
package:build_runner_core/src/generate/build_impl.dart 323:20 _SingleBuild._runPhases.<fn>.<fn>
dart:async _completeOnAsyncReturn
package:build_runner_core/src/generate/build_impl.dart _SingleBuild._matchingPrimaryInputs
[SEVERE] Build:
Failed after 604ms
pub finished with exit code 1
#0 throwToolExit (package:flutter_tools/src/base/common.dart:28:3)
#1 pubInteractively (package:flutter_tools/src/dart/pub.dart:191:5)
<asynchronous suspension>
#2 PackagesPassthroughCommand.runCommand (package:flutter_tools/src/commands/packages.dart:227:11)
<asynchronous suspension>
#3 FlutterCommand.verifyThenRunCommand (package:flutter_tools/src/runner/flutter_command.dart:490:18)
#4 _asyncThenWrapperHelper.<anonymous closure> (dart:async-patch/async_patch.dart:71:64)
#5 _rootRunUnary (dart:async/zone.dart:1132:38)
#6 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
#7 _FutureListener.handleValue (dart:async/future_impl.dart:137:18)
#8 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:678:45)
#9 Future._propagateToListeners (dart:async/future_impl.dart:707:32)
#10 Future._completeWithValue (dart:async/future_impl.dart:522:5)
#11 Future._asyncComplete.<anonymous closure> (dart:async/future_impl.dart:552:7)
#12 _rootRun (dart:async/zone.dart:1124:13)
#13 _CustomZone.run (dart:async/zone.dart:1021:19)
#14 _CustomZone.runGuarded (dart:async/zone.dart:923:7)
#15 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:963:23)
#16 _microtaskLoop (dart:async/schedule_microtask.dart:41:21)
#17 _startMicrotaskLoop (dart:async/schedule_microtask.dart:50:5)
#18 _runPendingImmediateCallback (dart:isolate-patch/isolate_patch.dart:116:13)
#19 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:173:5)
Code sample
part 'ThumbnailPicture.g.dart';
class ThumbnailPicture extends StatefulWidget {
@HiveField(0)
Uint8List byteData;
@override
_ThumbnailPictureState createState() => _ThumbnailPictureState();
}
Version
Steps to Reproduce
Put a key value pair in a box, delete the key, => the key is really deleted
Restart the app => the key is back
Code sample
//this doesn't work
await box.delete(collectionName);
//I had to use deleteAll as a workaround
await box.deleteAll([collectionName]);
Version
How do I store a list of my class myClass
?
I get an error {
Cannot write unknown data type : myClass
}
Thanks.
Hey, first of all hive is a pretty sweet library and the need to not pass down boxes simplifies development by a ton. I am using it for an App in production, but I ran into a problem. It's more like a performance issue though.
I have a list of objects, rather than using the type adapter I'm storing it as a list of maps and it seems to work pretty well. But what if I want to append to the stored list. Will the entire list be rewritten into the box. Wouldn't it cause any performance issues down the line? Is there any better way to do this ?
I was reading about the way the types are modelled here:
https://hivedb.github.io/hive/#/generate_adapter
The numbering of each field is the exact same approach as GRPC / Protobufs.
SO i was thinking of writing a converter so that on the Server side you can reuse your protobufs to generate the hive types that the hive generator will use.
What do you think ?
I'd like to use Hive as a temporary cache for resources.
Setup would be done with a TTL field that can be set at the Box and write method level.
box.putAll({'key1': 'value1', 42: 'life'}, ttl: const Duration(seconds:30))
Is this a feature in the scope of Hive ?
Thanks
While trying to import the library, I'm getting the following errors:
[WARNING]build_web_compilers:entrypoint on web/main.dart: Unable to read hive|lib/hive.ddc.js, check your console or the `.dart_tool/build/generated/hive/lib/hive.ddc.js.errors` log file.
[SEVERE]build_web_compilers:entrypoint on web/main.dart: AssetNotFoundException: hive|lib/hive.ddc.js
Steps to Reproduce
Add hive as package to pubsec and call showLicensePage()
The license of hive package throw a exception in showLicensePage
Version
Why isn't Hive ready for production?
I've been testing Hive for months, and I'm tempted to get Hive up and running on an app with 2 million users.
I needed a Lightweight dart library (my bridge with native code is already too overloaded, so it had to be 100% dart) that would allow simple storage of user settings (night mode, notification settings, and so on). your username and avatar downloaded from the API), and Hive has outperformed me on numerous issues over Seembast that they claim is in production. The main thing that makes Hive a killer of anything that stores data is being able to use it synchronously. Man, you made me delete 600 lines of code in futurebuilders, I almost didn't believe it when I found Hive.
Thanks for keeping up the good work in this library!
And I hope to know the risks I am taking, as I am about to use it even for storing self-destructive messages from a chat application (the key would be the username of the conversation, the value a map, which is self destructive , would be passed to a message list, displayed on screen, and deleted from Hive) this other app has 700,000 users.
Steps to Reproduce
When clicking on the sample link in hive/example
(or the corresponding "example" tab on the pub site), it's displaying a 404 error.
Why is this happening?
The reason it's not working is that the samples directory moved into a top-level repo in the hivedb organisation from https://github.com/hivedb/hive/tree/master/examples (not working) to https://github.com/hivedb/samples.
Solution
The link should be updated.
Steps to Reproduce
just entered your website.
Although that might be because i've tested your todo app before a few days or weeks ago, almost the same day you lauched that example. I don't know if that old information stored on my browser that caused this.
Code sample
instead i will provide a picture
Version
Question
As far as I can tell there's no documented way of unit integration testing with Hive.
Could we consider adding a test suite to one of the examples?
Code sample
N/A
Version
Any way to be notified of a type changing and so to update the widget ?
This is my HiveHelper class
class HiveHelper {
open() async {
Directory appDocDir = await getApplicationDocumentsDirectory();
String dbFilePath = [appDocDir.path, 'majesty_database'].join('/');
Hive.init(dbFilePath);
// Box For UserDetail
var box = await Hive.openBox(Boxes.userDetail); // This is where code breaks
box.registerAdapter(UserDetailAdapter(), 0);
}
close() {
Hive.close();
}
}
class Boxes {
static final String userDetail = 'user_detail';
}
And in main.dart
void main() async {
HiveHelper _hiveHelper = HiveHelper();
await _hiveHelper.open();
runApp(MajestyApp());
}
This code runs successfully on the first couple times. After maybe third or fourth time it breaks at the box opening in the open method in HiveHelper class and gives me the following error
E/flutter (20679): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: HiveError: Cannot read, unknown typeId: 32. Did you forget to register an adapter?
E/flutter (20679): #0 BinaryReaderImpl.read (package:hive/src/binary/binary_reader_impl.dart:243:9)
E/flutter (20679): #1 Frame.decodeValue (package:hive/src/binary/frame.dart:89:22)
E/flutter (20679): #2 Frame.decode (package:hive/src/binary/frame.dart:78:19)
E/flutter (20679): #3 FrameIoHelper.framesFromFile (package:hive/src/io/frame_io_helper.dart:77:25)
E/flutter (20679): <asynchronous suspension>
E/flutter (20679): #4 StorageBackendVm.initialize (package:hive/src/backend/storage_backend_vm.dart:85:25)
E/flutter (20679): <asynchronous suspension>
E/flutter (20679): #5 BoxBase.initialize (package:hive/src/box/box_base.dart:87:20)
E/flutter (20679): #6 HiveImpl.openBoxInternal (package:hive/src/hive_impl.dart:92:15)
E/flutter (20679): <asynchronous suspension>
E/flutter (20679): #7 HiveImpl.openBox (package:hive/src/hive_impl.dart:72:23)
E/flutter (20679): <asynchronous suspension>
E/flutter (20679): #8 HiveHelper.open (package:ninja_app/src/service/local_database/hive_helper.dart:24:26)
E/flutter (20679): <asynchronous suspension>
E/flutter (20679): #9 main (package:ninja_app/main.dart:43:21)
E/flutter (20679): #10 _AsyncAwaitCompleter.start (dart:async-patch/async_patch.dart:43:6)
E/flutter (20679): #11 main (package:ninja_app/main.dart:27:10)
E/flutter (20679): #12 _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:229:25)
E/flutter (20679): #13 _rootRun (dart:async/zone.dart:1124:13)
E/flutter (20679): #14 _CustomZone.run (dart:async/zone.dart:1021:19)
E/flutter (20679): #15 _runZoned (dart:async/zone.dart:1516:10)
E/flutter (20679): #16 runZoned (dart:async/zone.dart:1500:12)
E/flutter (20679): #17 _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:221:5)
E/flutter (20679): #18 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:305:19)
E/flutter (20679): #19 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:172:12)
It will also be great if you have simple flutter todo app example.
Version
Hi,
First off, thanks for this fantastic package! I just replaced both Shared Preferences and Secure Storage with Hive and am thrilled to have a single solution. Well done!
The issue in question is happening during my integration testing (using flutter_driver
), which at this point is just a simple test to login to my app. Prior to Hive, this worked fine. After Hive, it now breaks with a seemingly unrelated error. Because of the unhelpful error, it took me a while to track it down.
Steps to Reproduce
I've created a minimal reproduction in this repo: https://github.com/jamesdixon/hive_flutter_driver_issue
flutter drive --target=test_driver/run_app.dart
Result (on Emulators):
DriverError: Error in Flutter application: Uncaught extension error while executing tap: 'package:flutter_driver/src/extension/extension.dart': Failed assertion: line 193 pos 14: 'WidgetsBinding.instance.isRootWidgetAttached || !command.requiresRootWidgetAttached': No root widget is attached; have you remembered to call runApp()?
Result (on physical iPhone):
FileSystemException: writeFrom failed, path = '' (OS Error: Input/output error, errno = 5)
Next, comment out line 12 of main.dart
where we use Hive to open a box.
Run the test command again and the result will be that all tests pass on both emulators and devices.
I'm not sure if this is a Flutter Driver error or a Hive error but figured I'd take a shot and post it here first :)
Version
Question
Hi, I wanted to try out Hive in my app, but unfortunately I came across an error when opening a box. The folder "hive" already exists and I use the iOS Simulator.
FileSystemException (FileSystemException: Creation failed, path = 'assets' (OS Error: Permission denied, errno = 13))
Code sample
Hive.init("assets/data/hive/");
await Hive.openBox("game");
var gameBox = Hive.box("game");
Version
I get the following exception HiveError: String contains non-ASCII characters.
whenever I write a Unicode string (currently, I am just trying to store some Arabic text as a String in the database).
Any thoughts on how to fix this? I'm happy to implement the fix if you provide some pointers.
hive can be added to FlutterArsenal to help with reach, accessibility and ease-of-use. Flutter Arsenal is a directory that is being curated for Flutter libraries and tool. The best way to do is by creating an issue on github.
Question
What's the correct way to use Hive for app theming (light/dark mode)?
Code sample
class Application extends StatelessWidget {
Future _openBoxes() async {
var dir = await getApplicationDocumentsDirectory();
Hive.init(dir.path);
return Future.wait([
Hive.openBox('settings'),
Hive.openBox('favorites'),
]);
}
Future _getTheme(BuildContext context) async {
var settingsBox = Hive.box('settings');
var theme = settingsBox.get('theme') ?? 'light';
print("Theme from box: $theme");
var materialTheme;
switch (theme) {
case 'light': {
materialTheme = ThemesStyles.light(context);
break;
}
case 'dark': {
materialTheme = ThemesStyles.dark(context);
break;
}
case 'black': {
materialTheme = ThemesStyles.black(context);
break;
}
default: materialTheme = ThemesStyles.light(context);
}
return materialTheme;
}
@override
Widget build(BuildContext context) {
final ThemeProvider themeProvider = Provider.of<ThemeProvider>(context);
return FutureBuilder(
future: _openBoxes(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
return FutureBuilder(
future: _getTheme(context),
builder: (BuildContext context, AsyncSnapshot snapshot) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: snapshot.hasData ? snapshot.data : ThemesStyles.black(context),
routes: routes(context),
home: ScrollConfiguration(
behavior: BounceScrollBehavior(),
child: HomePage(),
)
);
}
);
}
);
}
}
Link to file: https://github.com/holt-soundboard/holt-soundboard-mobile/blob/master/lib/main.dart
As seen, I have nested FutureBuilders()
, one for opening boxes, one for getting the theme, which I thought would work. However, this doesn't work in production (release app).
Version
Question
What are your plans for maintaining this package? We are thinking of using Hive in our production app. We want to know if you will be maintaining Hive actively.
Can I replace sqlite to hive (SELECT * USERS WHERE ID > 0 AND gender LIKE "male" OR name LIKE "%ohn%" SORT BY age DESC )
Or this plugin work only with key-valur pair?
In the future I want to support syncing Hive with a remote database.
It would be helpful if you could share your needs & ideas.
One of the most obvious use cases is backing up data (for example settings or messages etc.) I think Firebase should be one of the first supported remotes.
Calling Hive.delete(key)
deletes the key when app is in use and keep working normally for changes on the box, but after killing and launching again Hive
always fetches the last state before the key deletion.
Open app first time
box.get(key)
-> ["123", "1234"]Hive.delete(key)
box.get(key)
-> []Kill app
Relaunch app
box.get(key)
-> ["123", "1234"] // should be []
I keep getting the following error from the autogenerated adapter.
I/flutter (30530): type 'List<dynamic>' is not a subtype of type 'List<String>'
My schema is below. The put works fine. It errors when I call get.
import 'package:hive/hive.dart';
part 'chapter.g.dart';
@HiveType()
class Chapter {
Chapter(
{this.number,
this.numVerses,
this.numSections,
this.sectionTitles,
this.sectionStartVerses,
this.verses});
@HiveField(0)
int number;
@HiveField(1)
int numVerses;
@HiveField(2)
int numSections;
@HiveField(3)
List<String> sectionTitles;
@HiveField(4)
List<int> sectionStartVerses;
@HiveField(5)
List<String> verses;
}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.