Giter VIP home page Giter VIP logo

hive's Introduction

Isar Database

QuickstartDocumentationSample AppsSupport & IdeasPub.dev

Isar [ee-zahr]:

  1. River in Bavaria, Germany.
  2. Crazy fast NoSQL database that is a joy to use.

⚠️ ISAR V4 IS NOT READY FOR PRODUCTION USE ⚠️
If you want to use Isar in production, please use the stable version 3.

Features

  • 💙 Made for Flutter. Easy to use, no config, no boilerplate
  • 🚀 Highly scalable The sky is the limit (pun intended)
  • 🍭 Feature rich. Composite & multi-entry indexes, query modifiers, JSON support etc.
  • Asynchronous. Parallel query operations & multi-isolate support by default
  • 🦄 Open source. Everything is open source and free forever!

Isar database can do much more (and we are just getting started)

  • 🕵️ Full-text search. Make searching fast and fun
  • 📱 Multiplatform. iOS, Android, Desktop
  • 🧪 ACID semantics. Rely on database consistency
  • 💃 Static typing. Compile-time checked and autocompleted queries
  • Beautiful documentation. Readable, easy to understand and ever-improving

Join the Telegram group for discussion and sneak peeks of new versions of the DB.

If you want to say thank you, star us on GitHub and like us on pub.dev 🙌💙

Quickstart

Holy smokes you're here! Let's get started on using the coolest Flutter database out there...

1. Add to pubspec.yaml

dependencies:
  isar: 4.0.0
  isar_flutter_libs: 4.0.0 # contains Isar Core

dev_dependencies:
  build_runner: any

2. Annotate a Collection

part 'email.g.dart';

@collection
class Email {
  Email({
    this.id,
    this.title,
    this.recipients,
    this.status = Status.pending,
  });

  final int id;

  @Index(type: IndexType.value)
  final String? title;

  final List<Recipient>? recipients;

  final Status status;
}

@embedded
class Recipient {
  String? name;

  String? address;
}

enum Status {
  draft,
  pending,
  sent,
}

3. Open a database instance

final dir = await getApplicationDocumentsDirectory();
final isar = await Isar.open(
  [EmailSchema],
  directory: dir.path,
);

4. Query the database

final emails = isar.emails.where()
  .titleContains('awesome', caseSensitive: false)
  .sortByStatusDesc()
  .limit(10)
  .findAll();

Isar Database Inspector

The Isar Inspector allows you to inspect the Isar instances & collections of your app in real-time. You can execute queries, edit properties, switch between instances and sort the data.

To launch the inspector, just run your Isar app in debug mode and open the Inspector link in the logs.

CRUD operations

All basic crud operations are available via the IsarCollection.

final newEmail = Email()..title = 'Amazing new database';

await isar.writeAsync(() {
  isar.emails.put(newEmail); // insert & update
});

final existingEmail = isar.emails.get(newEmail.id!); // get

await isar.writeAsync(() {
  isar.emails.delete(existingEmail.id!); // delete
});

Database Queries

Isar database has a powerful query language that allows you to make use of your indexes, filter distinct objects, use complex and(), or() and .xor() groups, query links and sort the results.

final importantEmails = isar.emails
  .where()
  .titleStartsWith('Important') // use index
  .limit(10)
  .findAll()

final specificEmails = isar.emails
  .filter()
  .recipient((q) => q.nameEqualTo('David')) // query embedded objects
  .or()
  .titleMatches('*university*', caseSensitive: false) // title containing 'university' (case insensitive)
  .findAll()

Database Watchers

With Isar database, you can watch collections, objects, or queries. A watcher is notified after a transaction commits successfully and the target changes. Watchers can be lazy and not reload the data or they can be non-lazy and fetch new results in the background.

Stream<void> collectionStream = isar.emails.watchLazy();

Stream<List<Post>> queryStream = importantEmails.watch();

queryStream.listen((newResult) {
  // do UI updates
})

Benchmarks

Benchmarks only give a rough idea of the performance of a database but as you can see, Isar NoSQL database is quite fast 😇

If you are interested in more benchmarks or want to check how Isar performs on your device you can run the benchmarks yourself.

Unit tests

If you want to use Isar database in unit tests or Dart code, call await Isar.initializeIsarCore(download: true) before using Isar in your tests.

Isar NoSQL database will automatically download the correct binary for your platform. You can also pass a libraries map to adjust the download location for each platform.

Make sure to use flutter test -j 1 to avoid tests running in parallel. This would break the automatic download.

Contributors ✨

Big thanks go to these wonderful people:


Alexis

Burak

Carlo Loguercio

Frostedfox

Hafeez Rana

Hamed H.

JT

Jack Rivers

Joachim Nohl

Johnson

LaLucid

Lety

Michael

Moseco

Nelson Mutane

Oscar Palomar

Peyman

Simon Choi

Ura

blendthink

mnkeis

nobkd

License

Copyright 2023 Simon Choi

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

hive's People

Contributors

abhishek01039 avatar afsar-pasha avatar dev-horacebg avatar dev-vickie avatar dipu-bd avatar inconnu08 avatar jgtm2024 avatar jibiel avatar jukqaz avatar kalildev avatar kranfix avatar krida2000 avatar krille-chan avatar limingnie avatar marcelgarus avatar marci002 avatar miltoneiji avatar nico-famedly avatar reprevise avatar ryojiro avatar saibotma avatar sergeshkurko avatar shroff avatar simc avatar sorunome avatar thecarpetmerchant avatar themisir avatar theonewiththebraid avatar victoruvarov avatar wenhaowu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

hive's Issues

RangeError on openBox() after put()

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

Unable to read List<String>

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;
}

Write binary format spec

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

Issue with Hive + Flutter Driver for Integration Tests

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

  1. Clone the repo
  2. Run 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

  • Platform: Mac
  • Flutter version: 1.9.1 hotfix 2
  • Hive version: 1.0.0

Type adapter throws not enough byte error on read after write

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): 

[QUESTION] query

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?

Load Hive from flutter assets

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.

[Question]

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?

Error with TypeAdapter

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

  • Platform: Android
  • Flutter version: v1.9.1+hotfix.2
  • Hive version: 1.0.0

Flutter Web AssetNotFoundException

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

Add hive to Flutter Arsenal

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.

To-Do App is broken

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
image

Version

  • Platform: Web
  • Browser: Google Chrome

Testing with Hive

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

  • Hive version: 1.0.0

License Exception

Steps to Reproduce
Add hive as package to pubsec and call showLicensePage()
The license of hive package throw a exception in showLicensePage

Version

  • Platform: iOS, Android, Mac, Windows, Linux, Web
  • Flutter version: 1.7.8+hotfix 4
  • Hive version: 0.5.0

What's the correct way to use Hive for app theming (light/dark mode)?

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

  • Platform: Android, Mac
  • Hive version: 1.0.0

RangeError running TypeAdapterGenerator with Uint8List

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

  • Platform: MacOS Mojave 10.14.6 (18G95)
  • Flutter version: v1.9.1+hotfix.2
  • Hive Generator version: 0.5.1
  • Build Runner version : 1.7.0

Need to know about active development.

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.

[hive_generator] Error when running

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

  • Flutter version: [1.9.1+hotfix.2]
  • Hive version: [1.0.0]
  • Hive generator version: [0.5.2]

Breaking changes

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?

[Question] HiveField 0 - 255 exclusive to one class?

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?

box.delete(dynamic key) doesn't work

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

  • Platform: Android
  • Flutter version: 1.9.1
  • Hive version: 1.0.0

Time To Live

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

Can Hive be used for state management?

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?

FileSystemException: Creation failed

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

  • Platform: iOS
  • Flutter version: 1.7.8
  • Hive version: 0.5.1
    Screenshot 2019-09-07 at 13 37 33

Failing on writing Unicode Strings

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.

[Feature Request] Easy to sync with back end server

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?

Unsuccessful flutter web builds

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

  • Platform: Web
  • Flutter version: 1.10.7-pre.69
  • Hive version: 1.0.0
  • Hive_flutter version: 0.2.1

Hive.deleter(key) Does not delete over relaunches

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

  • Save value ["123"] into key
  • Save value ["1234"] into key
  • Fetch box.get(key) -> ["123", "1234"]
  • Call Hive.delete(key)
  • Fetch box.get(key) -> []

Kill app

Relaunch app

  • Fetch box.get(key) -> ["123", "1234"] // should be []

Exception caught when box.put is called

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

Why does the documentation say it is not ready for production?

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.

Make generic TypeAdapters possible

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?

Support final attributes

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?

ChangeNotifier

Any way to be notified of a type changing and so to update the widget ?

`HiveError('Not all bytes have been used.')` in `Hive.init()`

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

How to use the Hive package in a sync data from server scenario?

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

  • Platform: Windows Android Simulator
  • Flutter version: [e.g. 1.9.1]
  • Hive version: [e.g. 1.0.0]

Do you recommend any Unique Key Generator?

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 ?

[Question] How to manipulate a list of objects ?

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 ?

Hive sync: Let's discuss it.

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.

Bad State No element when putting a Map into a Box

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
Screen Shot 2019-09-14 at 3 05 12 PM

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

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.