hive_ce 2.11.0-pre.4 copy "hive_ce: ^2.11.0-pre.4" to clipboard
hive_ce: ^2.11.0-pre.4 copied to clipboard

Hive Community Edition - A spiritual continuation of Hive v2

Fast, Enjoyable & Secure NoSQL Database

Dart CI codecov Pub Version License

PubStats Popularity PubStats Rank PubStats Dependents

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

Tutorial #

For a quick tutorial, see this wonderful post by Tijn van den Eijnde

Features #

  • 🚀 Cross platform: mobile, desktop, browser
  • ⚡ Great performance (see benchmark)
  • ❤️ Simple, powerful, & intuitive API
  • 🔒 Strong encryption built in
  • 🎈 NO native dependencies
  • 🔋 Batteries included

New features in Hive CE #

Hive CE is a spiritual continuation of Hive v2 with the following new features:

  • Isolate support through IsolatedHive
  • Flutter web WASM support
  • Automatic type adapter generation using the GenerateAdapters annotation
    • No more manually adding annotations to every type and field
    • Generate adapters for classes outside the current package
  • A HiveRegistrar extension that lets you register all your generated adapters in one call
  • Extends the maximum type ID from 223 to 65439
  • Support for constructor parameter defaults
  • Support for Sets
  • A built in Duration adapter
  • Freezed support
  • Support for generating adapters with classes that use named imports

Benchmark #

This is a comparison of the time to complete a given number of write operations and the resulting database file size:

Operations Hive CE Time IsolatedHive Time Hive CE Size Hive v4 Time Hive v4 Size
10 0.00 s 0.00 s 0.00 MB 0.00 s 1.00 MB
100 0.00 s 0.01 s 0.01 MB 0.01 s 1.00 MB
1000 0.02 s 0.03 s 0.11 MB 0.06 s 1.00 MB
10000 0.13 s 0.25 s 1.10 MB 0.64 s 5.00 MB
100000 1.40 s 2.64 s 10.97 MB 7.26 s 30.00 MB
1000000 19.94 s 41.50 s 109.67 MB 84.87 s 290.00 MB

Database size in Hive v4 is directly affected by the length of field names in model classes which is not ideal. Also Hive v4 is much slower than Hive CE for large numbers of operations.

IsolatedHive is slower than Hive, but it is much faster than Hive v4 and you still get the benefit of multiple isolate support.

The benchmark was performed on an M3 Max MacBook Pro. You can see the benchmark code here.

Migration guides #

Usage #

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

import 'package:hive_ce/hive.dart';

void example() {
  final box = Hive.box('myBox');
  box.put('name', 'David');
  final name = box.get('name');
  print('Name: $name');
}

copied to clipboard

Guides #

IsolatedHive (isolate support)

IsolatedHive allows you to safely use Hive in a multi-isolate environment by maintaining its own separate isolate for Hive operations

Here are some common examples of multi-isolate scenarios:

IsolatedHive has a very similar API to Hive, but there are some key differences:

  • The init call takes an isolateNameServer parameter
  • Most methods are asynchronous due to isolate communication
  • IsolatedHive does not support HiveObject or HiveList
  • Isolate communication does add some overhead. See the benchmarks above.

NOTE: On web, IsolatedHive directly calls Hive since web does not support isolates

Usage #

import 'package:hive_ce/hive.dart';

import 'stub_ins.dart';

void main() async {
  await IsolatedHive.init('.', isolateNameServer: StubIns());
  final box = await IsolatedHive.openBox('box');
  await box.put('key', 'value');
  print(await box.get('key')); // reading is async
}

copied to clipboard

NOTE: It is possible to use IsolatedHive without an IsolateNameServer, BUT THIS IS UNSAFE. The IsolateNameServer is what allows IsolatedHive to locate and communicate with a single backend isolate.

Additional notes:

  • With Flutter, use IsolatedHive.initFlutter from hive_ce_flutter to initialize IsolatedHive with Flutter's IsolateNameServer
  • There is also an IsolatedHive.registerAdapters method if you use hive_ce_generator to generate adapters

Example #

See an example of a multi-window Flutter app using IsolatedHive here

Store objects

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

Create model classes #

import 'package:hive_ce/hive.dart';

class Person extends HiveObject {
  Person({required this.name, required this.age});

  String name;
  int age;
}

copied to clipboard

Create a GenerateAdapters annotation #

Usually this is placed in lib/hive/hive_adapters.dart

import 'package:hive_ce/hive.dart';
import 'person.dart';

@GenerateAdapters([AdapterSpec<Person>()])
part 'hive_adapters.g.dart';

copied to clipboard

Update pubspec.yaml #

dev_dependencies:
  build_runner: latest
  hive_ce_generator: latest
copied to clipboard

Run build_runner #

dart pub run build_runner build --delete-conflicting-outputs
copied to clipboard

This will generate the following:

  • TypeAdapters for the specified AdapterSpecs
  • TypeAdapters for all explicitly defined HiveTypes
  • A hive_adapters.g.dart file containing all adapters generated from the GenerateAdapters annotation
  • A hive_adapters.g.yaml file
  • A hive_registrar.g.dart file containing an extension method to register all generated adapters

All of the generated files should be checked into version control. These files are explained in more detail below.

Use the Hive registrar #

The Hive Registrar allows you to register all generated TypeAdapters in one call

import 'dart:io';
import 'package:hive_ce/hive.dart';
import 'package:your_package/hive/hive_registrar.g.dart';

void main() {
  Hive
    ..init(Directory.current.path)
    ..registerAdapters();
}
copied to clipboard

Using HiveObject methods #

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

import 'package:hive_ce/hive.dart';
import 'person.dart';

void example() async {
  final box = await Hive.openBox('myBox');

  final person = Person(name: 'Dave', age: 22);
  await box.add(person);

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

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

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

copied to clipboard

About hive_adapters.g.yaml #

The Hive schema is a generated yaml file that contains the information necessary to incrementally update the generated TypeAdapters as your model classes evolve.

Some migrations may require manual modifications to the Hive schema file. One example is class/field renaming. Without manual intervention, the generator will see both an added and removed class/field. To resolve this, manually rename the class/field in the schema.

Explicitly defining HiveTypes #

The old method of defining HiveTypes is still supported, but should be unnecessary now that Hive CE supports constructor parameter defaults. If you have a use-case that GenerateAdapters does not support, please create an issue on GitHub.

Unfortunately it is not possible for GenerateAdapters to handle private fields. You can use @protected instead if necessary.

BoxCollection

BoxCollections are a set of boxes which can be similarly used as normal boxes, except of that they dramatically improve speed on web. They support opening and closing all boxes of a collection at once and more efficiently store data in indexed DB on web.

Aside, they also expose Transactions which can be used to speed up tremendous numbers of database transactions on web.

On dart:io platforms, there is no performance gain by BoxCollections or Transactions. Only BoxCollections might be useful for some box hierarchy and development experience.

import 'package:hive_ce/hive.dart';
import 'hive_cipher_impl.dart';

void example() async {
  // Create a box collection
  final collection = await BoxCollection.open(
    // Name of your database
    'MyFirstFluffyBox',
    // Names of your boxes
    {'cats', 'dogs'},
    // Path where to store your boxes (Only used in Flutter / Dart IO)
    path: './',
    // Key to encrypt your boxes (Only used in Flutter / Dart IO)
    key: HiveCipherImpl(),
  );

  // Open your boxes. Optional: Give it a type.
  final catsBox = await collection.openBox<Map>('cats');

  // Put something in
  await catsBox.put('fluffy', {'name': 'Fluffy', 'age': 4});
  await catsBox.put('loki', {'name': 'Loki', 'age': 2});

  // Get values of type (immutable) Map?
  final loki = await catsBox.get('loki');
  print('Loki is ${loki?['age']} years old.');

  // Returns a List of values
  final cats = await catsBox.getAll(['loki', 'fluffy']);
  print(cats);

  // Returns a List<String> of all keys
  final allCatKeys = await catsBox.getAllKeys();
  print(allCatKeys);

  // Returns a Map<String, Map> with all keys and entries
  final catMap = await catsBox.getAllValues();
  print(catMap);

  // delete one or more entries
  await catsBox.delete('loki');
  await catsBox.deleteAll(['loki', 'fluffy']);

  // ...or clear the whole box at once
  await catsBox.clear();

  // Speed up write actions with transactions
  await collection.transaction(
    () async {
      await catsBox.put('fluffy', {'name': 'Fluffy', 'age': 4});
      await catsBox.put('loki', {'name': 'Loki', 'age': 2});
      // ...
    },
    boxNames: ['cats'], // By default all boxes become blocked.
    readOnly: false,
  );
}

copied to clipboard
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 and initializing Hive, you can use Hive in your project:

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

class SettingsPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder(
      valueListenable: Hive.box('settings').listenable(),
      builder: (context, box, widget) {
        return Switch(
          value: box.get('darkMode'),
          onChanged: (val) {
            box.put('darkMode', val);
          }
        );
      },
    );
  }
}
copied to clipboard

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

210
likes
160
points
83.9k
downloads

Publisher

verified publisheriodesignteam.com

Weekly Downloads

2024.09.03 - 2025.03.18

Hive Community Edition - A spiritual continuation of Hive v2

Repository (GitHub)

Documentation

Documentation
API reference

License

Apache-2.0, BSD-3-Clause (license)

Dependencies

crypto, isolate_channel, meta, web

More

Packages that depend on hive_ce