hive 1.1.1

  • Readme
  • Changelog
  • Example
  • Installing
  • 97

Dart CI Codecov Core version

Hive is a lightweight and blazing fast key-value database written in pure Dart. Inspired by Bitcask.

Flutter Web Demos πŸ•ΈοΈ #

Features #

Cross-platform ⚑ #

  • Runs on desktop, mobile & in browser
  • Very good performance (see benchmark)

Easy to use ❀️ #

  • Keys are of type String or uint32 and values are arbitrary objects
  • The basic operations are put(key, value), get(key), delete(key)
  • Strong encryption built in

Lightweight 🎈 #

  • Small runtime
  • Small disk space consumption
  • NO native dependencies

Benchmark #

Read 1000 entriesWrite 1000 entries
SharedPreferences is on par with Hive when it comes to read performance. SQLite performs much worse.Hive greatly outperforms SQLite and SharedPreferences when it comes to writing or deleting.

This benchmark was performed on a Oneplus 6T with Android Q. All entries are read and written one after another. You can run the benchmark yourself.

Getting started #

To get started using Hive in a Flutter project, add the following dependencies to your pubspec.yaml. Use the latest version instead of [version].

Core version Generator version Hive Flutter version Build runner version

dependencies:
  hive: ^[version]
  hive_flutter: ^[version]

dev_dependencies:
  hive_generator: ^[version]
  build_runner: ^[version]

Usage #

You can use Hive just like a map. It is not necessary to await Futures.

Hive.init(Directory.current.path);
var box = await Hive.openBox('myBox');

box.put('name', 'David');

var name = box.get('name');

print('Name: $name');

Store objects #

Hive not only supports primitives, lists and maps but also any Dart object you like. You need to generate a type adapter before you can store objects.

@HiveType
class Person extends HiveObject {

  @HiveField(0)
  String name;

  @HiveField(1)
  int age;
}

Extending HiveObject is optional but it provides handy methods like save() and delete().

Hive.init(Directory.current.path);
var box = await Hive.openBox('myBox');

var person = Person()
  ..name = 'Dave'
  ..age = 22;
box.add(person);

print(box.getAt(0)); // Dave - 22

person.age = 30;
person.save();

print(box.getAt(0)) // Dave - 30

Hive ❀️ Flutter #

Hive was written with Flutter in mind. It is a perfect fit if you need a lightweight datastore for your app. After adding the required dependencies to your pubspec.yaml, you are able to use Hive in your project:

import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';

class SettingsPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return WatchBoxBuilder(
      box: Hive.box('settings'),
      builder: (context, box) {
        return Switch(
          value: box.get('darkMode'),
          onChanged: (val) {
            box.put('darkMode', val);
          }
        )
      },
    );
  }
}

Boxes are cached and therefore fast enough to be used directly in the build() method of Flutter widgets.

Todo #

The work on Hive has just started. If you want to contribute, it would be amazing if you helped me with one of these:

  • [x] Good test coverage
  • [x] Many examples, especially for Flutter
  • [x] Benchmarks and comparison
  • [x] Finalize API
  • [x] Even more tests
  • [ ] Queries
  • [ ] Improve documentation
  • [ ] Write binary format spec
  • [ ] You can never have enough tests

Licence #

Copyright 2019 Simon Leier

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.

1.1.1 #

Breaking changes #

  • object.delete() now throws exception if object is not stored in a box

Fixes #

  • Fixed bug where object.save() would faild on subsequent calls

1.1.0+2 #

Fixes #

  • Fixed bug that it was not possible to open typed boxes (Box<E>)

1.1.0+1 #

Fixes #

  • Fixed bug that corrupted boxes were not detected

1.1.0 #

Breaking changes #

  • Changed return type of addAll() from List<int> to Iterable<int>.
  • Removed the option to register TypeAdapters for a specific box. E.g. box.registerTypeAdapter().
  • getAt(), putAt(), deleteAt() and keyAt() no longer allow indices out of range.

Enhancements #

  • Added HiveObject
  • Boxes have now an optional type parameter Box<E>
  • Support opening boxes from assets

Fixes #

  • Fixed bug which was caused by not awaiting write operations
  • Fixed bug where custom compaction strategy was not applied
  • Hive now locks box files while they are open to prevent concurrent access from multiple processes

More #

  • Improved performance of putAll(), deleteAll(), add(), addAll()
  • Changed values parameter of addAll() from List to Iterable
  • Improved documentation
  • Preparation for queries

1.0.0 #

  • First stable release

0.5.1+1 #

  • Change keys parameter of deleteAll from List to Iterable
  • Fixed bug in BinaryWriter

0.5.1 #

  • Fixed Hive.init() bug in browser
  • Fixed a bug with large lists or strings
  • Improved box opening time in browser
  • Improved general write performance
  • Improved docs
  • Added integration tests

0.5.0 #

  • Added keyComparator parameter for custom key order
  • Added isEmpty and isNotEmpty getters to box
  • Added support for reading and writing subclasses
  • Removed length limitation for Lists, Maps and Strings
  • Greatly improved performance of storing Uint8Lists in browser
  • Removed CRC check in browser (not needed)
  • Improved documentation
  • TypeIds are now allowed in the range of 0-223
  • Fixed compaction
  • Fixed writing longer Strings
  • Breaking: Binary format changed

0.4.1+1 #

  • Document all public APIs
  • Fixed flutter_web error

0.4.1 #

  • Allow different versions of the path package

0.4.0 #

  • Added BigInt support
  • Added compactionStrategy parameter
  • Added automatic crash recovery
  • Added add() and addAll() for auto increment keys
  • Added getAt(), putAt() and deleteAt() for working with indices
  • Support for int (32 bit unsigned) keys
  • Non-lazy boxes now notify their listeners immediately about changes
  • Bugfixes
  • More tests
  • Breaking: Open boxes with openBox()
  • Breaking: Writing null is no longer equivalent to deleting a key
  • Breaking: Temporarily removed support for transactions. New API design needed. Will be coming back in a future version.
  • Breaking: Binary format changed
  • Breaking: API changes

0.3.0+1 #

  • Bugfix: Hive['yourBox'] didn't work with uppercase box names

0.3.0 #

  • Big step towards stable API
  • Support for transactions
  • Annotations for hive_generator
  • Bugfixes
  • Improved web support
  • Breaking: inMemory -> lazy
  • Breaking: Binary format changed

0.2.0 #

  • Support for dart2js
  • Improved performance
  • Added inMemory option
  • Breaking: Minor API changes
  • Breaking: Changed Endianness to little
  • Breaking: Removed Migrator

0.1.1 #

  • Downgrade to meta: ^1.1.6 to support flutter

0.1.0 #

  • First release

example/lib/main.dart

import 'dart:io';

import 'package:hive/hive.dart';

part 'main.g.dart';

@HiveType()
class Person {
  @HiveField(0)
  String name;

  @HiveField(1)
  int age;

  @HiveField(2)
  List<String> friends;

  @override
  String toString() {
    return '$name: $age';
  }
}

void main() async {
  var path = Directory.current.path;
  Hive.init(path);

  var box = await Hive.openBox('testBox');

  var person = Person()
    ..name = 'Dave'
    ..age = 22
    ..friends = ['Linda', 'Marc', 'Anne'];

  box.put('dave', person);

  print(box.get('dave')); // Dave: 22
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  hive: ^1.1.1

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter pub get

Alternatively, your editor might support pub get or flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:hive/hive.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
95
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
97
Learn more about scoring.

We analyzed this package on Nov 11, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.6.0
  • pana: 0.12.21

Platforms

Detected platforms: Flutter, web, other

No platform restriction found in primary library package:hive/hive.dart.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.5.0 <3.0.0
meta ^1.1.7 1.1.8
path >=1.6.0 <1.7.0 1.6.4
pointycastle ^1.0.1 1.0.1
Dev dependencies
mockito ^4.1.1
pedantic 1.7.0
test ^1.9.1