GithubHelp home page GithubHelp logo

isar / hive Goto Github PK

View Code? Open in Web Editor NEW
3.9K 59.0 387.0 1.13 MB

Lightweight and blazing fast key-value database written in pure Dart.

License: Apache License 2.0

Dart 100.00%
flutter dart key-value nosql encryption hive database

hive's Introduction

Fast, Enjoyable & Secure NoSQL Database

Hive is a lightweight and buzzing-fast key-value database made for Flutter and Dart.

Features ๐ŸŒŸ

  • ๐ŸŒ Bee everywhere: mobile, desktop, browser
  • ๐Ÿš€ Buzzing speed: Faster than a bee on caffeine!
  • ๐Ÿ’ก Sweet, powerful, & intuitive API
  • ๐Ÿ” Queen's Guard: Encryption built right in.
  • ๐Ÿง  Thinking in swarms: Multi-isolate support.
  • ๐Ÿฏ Everything a bee needs and more!

Bee fact: A single bee can visit 5,000 flowers in a day!

Buzz into Action ๐Ÿ

Feeling the excitement? Great! Let's help you take your first flight with Hive.

๐Ÿ”— Add dependencies

To kickstart the journey add hive, isar_flutter_libs and path_provider to your pubspec.yaml.

dependencies:
  hive: ^4.0.0
  isar_flutter_libs: ^4.0.0-dev.13
  path_provider: ^2.1.0

Pssst! ๐Ÿคซ path_provider will help you to find the optimal directory for each platform.

๐Ÿก Designate a Home

Hive needs a place to call home. Using path_provider we can find a valid directory.

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final dir = await getApplicationDocumentsDirectory();
  Hive.defaultDirectory = dir.path;

  // ...
}

๐Ÿ And... Action!

Woohoo! You're all set. Jump in and let your Hive adventure begin!

import 'package:hive/hive.dart';

final box = Hive.box();
box.put('name', 'David');

final name = box.get('name');
print('Name: $name');

Bee fact: Honeybees can fly at a speed of up to 30 kilometers per hour!

๐Ÿ“š Hive Handbook

In Hive, data is neatly organized into containers known as boxes. Think of boxes as tables you'd find in SQL, but far more flexible โ€” they don't stick to a set structure and can contain a variety of data. Boxes can be encrypted to store sensitive data.

Table of Contents

Want to jump to a specific section? Here's a handy table of contents:

Bee fact: Bees have five eyes โ€“ three simple eyes on top of the head, and two compound eyes, with numerous hexagonal facets.

๐Ÿ“ฆ Opening Boxes

Your journey with Hive begins with opening your first box. Trust me, it's unbee-lievably easy:

final box = Hive.box(name: 'myBox');

When you call Hive.box(name: 'myBox') for the first time with a given name, Hive will create a new box for you. If you call it again with the same name, Hive will return the already existing box.

You can also use Hive.box() without providing a name. In this case, Hive will return the default box.

There are optional parameters you can pass to Hive.box():

Parameter Description
name Label your box with a distinct name
directory Select a home for your box. If omitted, Hive uses the defaultDirectory.
encryptionKey Hand over this key, and Hive will encrypt your box. Keep it safe!
maxSizeMiB The maximum size of the box in MiB. Go for a modest number.

Bee fact: Beeswax, which is secreted from the abdomen of worker bees, is used to construct the honeycomb.

๐ŸŒ‚ Bidding Adieu: Closing Boxes

It's not advised to close boxes that might be accessed again. This prevents unnecessary overhead of reopening the box and ensures smooth data retrieval.

To close a box just call box.close(). Wipe the box from the face of the earth with box.deleteFromDisk().

Bee fact: When a bee finds a good source of nectar, it flies back to the hive and shows its friends where the nectar source is by doing a dance.

โœ๏ธ Filling the Honeycomb: Inserting Data

Once we have a box, it's time to fill it with sweet data! At its core, a box is just a key-value store. String keys are mapped to arbitrary primitive values. You can think of a box as a persisted Map<String, dynamic>.

final box = Hive.box();
box.put('danceMoves', 'Waggle Dance');
box.put('wingSpeed', 200);

Updating values? If a particular key already exists, Hive simply updates its corresponding value. And complex types like lists and maps? They're in too!

box.put('friends', ['Buzzy', 'Stinger', 'Honey']);
box.put('memories', {'firstFlight': 'Sunny Day', 'bestNectar': 'Rose'});

Instead of .put() you prefer the syntax of maps? Hive gets you:

box['danceMoves'] = 'Round Dance';
box['wingSpeed'] = 220;

Got a bucket of honey facts? Drop them all at once with box.putAll():

box.putAll({'favoriteFlower': 'Lavender', 'wingSpeed': 210});

Bee fact: A single bee colony can produce anywhere from 30 to 100 pounds of honey in a year, depending on the availability of nectar sources.

๐Ÿ‘€ Extracting Honey... I mean, Data!

Need a snippet of info from your Hive? No need to don the beekeeper suit; just scoop it out using box.get() or box.getAll(). If a key doesn't exist, box.get() simply return a null. But fret not; you can tell it to have a backup plan:

final box = Hive.box(name: 'beeees');
final fav = box.get('favoriteFlower');
final moves = box.get('danceMoves', defaultValue: 'waggle');

Oh, and if you're feeling fancy, use the [] operator for a more stylish approach:

final fav = box['favoriteFlower'];
final moves = box['danceMoves'] ?? 'waggle';

Bee fact: Worker bees are the only bees most people ever see flying around outside the hive. They're female, and their roles are to forage for food, build and protect the hive, and more.

๐Ÿงน Deleting Data

Time for some spring cleaning in the hive! To remove a single entry from your box, use box.delete():

final deleted = box.delete('lavenderHoney');
print('Honey eaten: $deleted'); // Honey eaten: true

Perhaps it's time for a complete reset, making space for a fresh batch of honey. If you're looking to remove all key-value pairs from a box, use box.clear():

box.clear();

Bee fact: Bees have been around for more than 30 million years! Their long history predates the existence of humans and even dinosaurs.

โœจ Using Boxes like Lists

In the bee world, honeycombs aren't just random compartments; they're methodically organized. Similarly, while we've been viewing Hive boxes as maps so far, they can be used just like lists:

final box = Hive.box();

box.add('Rose');
box.add('Tulip');

print(box.getAt(0)); // Rose
print(box.getAt(1)); // Tulip

But remember, bees can't retrieve honey from a comb that's empty or doesn't exist. Likewise, index-based operations will throw an error if you try an index out of bounds:

final box = Hive.box();
box.add('Daisy');
print(box.getAt(1)); // Error! This will make the bees buzz in confusion

Even if we insert a key-value pair we can still access the values by index.

final box = Hive.box();

box.add('Lily');
box.put('key', 'Orchid');

print(box.getAt(0)); // Lily
print(box.getAt(1)); // Orchid

Of course, we can also use the [] operator in combination with indexes :

final box = Hive.box();

box.add('Marigold');
print(box[0]); // Marigold

box[0] = 'Daffodil';
box[1] = 'Bluebell'; // Error! This will get the bees in a whirl

Bee fact: To produce one pound of honey, a hive's bees must visit 2 million flowers and fly over 55,000 miles.

๐Ÿ›ก๏ธ Type safety

Safety is the bee's priority! To keep your data sweet and pure boxes have an optional generic type parameter. It allows you to store only values of a specific type in a box:

final box = Hive.box<String>(name: 'BeeTreasures');
box.put('DaisyDance', 'SweetNectarShake');
box.put('RoseRumba', 'GoldenPollenParty');
box.put('TulipTango', 777); // Error - You can't fool the bees!

Make sure to use the same type whenever you get the box. Otherwise, you'll get an error:

Hive.box<int>(name: 'BeeTreasures'); // Error - We already have a String box!

Bee fact: Bees have two stomachs. One is for eating, and the other is for storing nectar collected from flowers or water so they can carry it back to their hive. Talk about a sweet backpack!

๐Ÿงฉ Bee-yond the Basics: Non-primitive Objects

Hive goes beyond storing just basic data types! Along with primitives, lists, and maps, Hive can store any Dart object of your liking. The only buzz you need to know? Your object should come equipped with a .fromJson() and .toJson() method:

class Bee {
  Bee({required this.name, required this.role});

  factory Bee.fromJson(Map<String, dynamic> json) => Bee(
    name: json['name'] as String,
    role: json['role'] as String,
  );

  final String name;
  final String role;

  Map<String, dynamic> toJson() => {
    'name': name,
    'role': role,
  };
}

Before our bee-friends can buzz around in Hive, you need to do the beekeeper's job and register the Bee class:

Hive.registerAdapter('Bee', Bee.fromJson);

Now, you're all set to let your bees fly:

final box = Hive.box();

final bumble = Bee(name: 'Bumble', role: 'Worker');
box.put('BumbleID', bumble);

print(box.get('BumbleID')); // Bumble - Worker

Bee fact: Bees are responsible for pollinating about one-third of the world's food crops.

๐Ÿชข Transactions

Transactions are an efficient way to update multiple values at once. They are also useful if you want to make sure that a Box is not changed by other code while you are working with it.

final box = Hive.box();

box.write(() {
  box.store('nectar1', 'GoldenNectar');
  box.store('nectar2', 'WildflowerBrew');
  box.store('nectar3', 'CloverDew');
});

box.read(() {
  box.get('nectar1'); // GoldenNectar
});

Changes made in a transaction are always atomic. Either all changes are applied or none of them. So if an error occurs during a transaction, the box will not be changed.

final box = Hive.box();
box.put('honeyLevel', 5);

box.write(() {
  box.put('honeyLevel', 6);
  throw Exception('Oh no!!!');
});

print(box.get('honeyLevel')); // 5

Bee fact: Bees can recognize human faces, and they can even be trained to associate a picture of a face with sweet treats!

๐Ÿ’ƒ The Isolate Dance

Just like a beehive where multiple bees work simultaneously, you can buzz into Hive from various Isolates at the same time. This nifty trick is great when you wish to keep those database activities separate from your UI thread.

Hive comes with a sweet Hive.compute() method that runs a function in a different isolate. The best part? It also does the honey-making job of setting up and tidying resources for you.

// Opening the bee's box
final box = Hive.box();

// Storing some sweet nectar
box.put('nectarType', 'wildflower');

await Hive.compute(() {
  // Accessing the same box from another worker bee
  final box = Hive.box();
  print(box.get('nectarType')); // wildflower

  // Updating the nectar's quality
  box.put('nectarType', 'lavender');
});

// Tasting the updated honey flavor
print(honeycomb.get('nectarType')); // lavender

Just remember, while the bees dance in harmony, ensure your Isolates do too! ๐Ÿ๐ŸŽถ

Bee fact: Bees have two pairs of wings, and they beat 11,400 times per minute.

๐Ÿฏ Buzzworthy Questions

๐Ÿ To bee or not to bee: Hive or Isar?

It's not always black and yellow! ๐Ÿ–ค๐Ÿ’› Both Hive and Isar have their sweet spots. Hive is a lightweight wrapper around Isar so if you are looking for a simple key-value store, Hive might be enough. Isar is the way to go if you need queries, relations, and more advanced features.

๐Ÿš€ Will using Hive make my app as fast as a bee?

While we can't promise your app will gain wings, ๐Ÿฆ‹ Hive sure will give it the speed it deserves. Hive is very resource efficient and optimized for mobile devices. Flutter like a butterfly, sting like a bee! ๐Ÿ

๐Ÿ—‚ Where in the beehive does Hive hide my honey... I mean, data?

Remember the defaultDirectory we set at the beginning? ๐Ÿ“ That's where Hive stores your data in a file named yourBoxName.isar or yourBoxName.sqlite.

๐Ÿ“ธ I've got some bee-autiful images! Can I store them directly in Hive?

While you might be tempted to put those pics right into Hive, ๐Ÿ–ผ๏ธ it's best to store your images and other binary data as files outside Hive. You can then store the file path in Hive. Think of it like leaving honey out in the open; it's better to keep it neatly stored in the appropriate place. ๐Ÿบ

๐Ÿ˜ฒ Yikes! What if my app meets an untimely demise (gets killed)? What becomes of my Hive?

No need for a bee-mergency! ๐Ÿšจ If your app buzzes off unexpectedly, Hive ensures that your data remains safe and sound. Transactions are atomic, so either all changes are applied or none of them. If an error occurs during a transaction, the box will not be changed.

๐Ÿ” How does Hive keep our data safe from sticky fingers?

We've got the queen's guard on duty! ๐Ÿ›ก๏ธ If you encrypt your box Hive uses 256-bit AES in CBC mode. Every database page is safeguarded separately, ensuring your sweet stuff remains secure and only accessible to those with the right key. Buzz-worthy protection, right? ๐Ÿ—๏ธ

๐Ÿค When should I rally the troops and use transactions?

Just like a hive making big decisions together, ๐ŸŒ you'll want to use transactions when you have several operations that should be executed together. If one fails, they all fail. It ensures your data stays consistent, safe, and buzzing in harmony! ๐ŸŽถ

๐Ÿคฃ What if I'm allergic to bees?

No worries! Hive is 100% sting-free, ๐Ÿšซ although we're pretty sure you'll get a buzz out of its performance.

โณ Hive operations are synchronous. Doesn't that make the bee waltz a bit slow?

Hive is incredibly fast and efficient. ๐Ÿš„ It's built on top of Isar, a high-performance database engine. If you want to keep database operations away from your UI isolate, you can use compute() or Isolate.run() to run them in a separate isolate.

๐Ÿ“ฆ How many boxes should a wise beekeeper have?

While the sky's the limit in the world of bees, ๐ŸŒŒ in Hive, every box becomes a separate file. So, even if you're buzzing with excitement, it's wise not to overdo it. ๐Ÿ“š

๐Ÿ“œ 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

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

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.

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

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

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

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

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]

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?

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.

[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]

[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?

ChangeNotifier

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

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

[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?

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]

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.

`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

[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?

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.

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?

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

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.

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?

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

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

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

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 []

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

[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 ?

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

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

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.

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

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?

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

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

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

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

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 ?

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.