hive
v2.2.3Lightweight and blazing fast key-value database written in pure Dart. Strongly encrypted using AES-256.
Архив пакета: https://pubdev.letsnova.ru/api/archives/hive/2.2.3.tar.gz
dart pub add hiveREADME
Fast, Enjoyable & Secure NoSQL Database
Hive is a lightweight and blazing fast key-value database written in pure Dart. Inspired by Bitcask.
Documentation & Samples 📖
If you need queries, multi-isolate support or links between objects check out Isar Database.
Features
- 🚀 Cross platform: mobile, desktop, browser
- ⚡ Great performance (see benchmark)
- ❤️ Simple, powerful, & intuitive API
- 🔒 Strong encryption built in
- 🎈 NO native dependencies
- 🔋 Batteries included
Getting Started
Check out the Quick Start documentation to get started.
Usage
You can use Hive just like a map. It is not necessary to await Futures.
var box = Hive.box('myBox');
box.put('name', 'David');
var name = box.get('name');
print('Name: $name');
BoxCollections
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.
// Create a box collection
final collection = await BoxCollection.open(
'MyFirstFluffyBox', // Name of your database
{'cats', 'dogs'}, // Names of your boxes
path: './', // Path where to store your boxes (Only used in Flutter / Dart IO)
key: HiveCipher(), // Key to encrypt your boxes (Only used in Flutter / Dart IO)
);
// Open your boxes. Optional: Give it a type.
final catsBox = 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,
);
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(typeId: 0)
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().
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 and initializing Hive, you can 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 ValueListenableBuilder(
valueListenable: Hive.box('settings').listenable(),
builder: (context, box, widget) {
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.
Benchmark
| 1000 read iterations | 1000 write iterations |
|---|---|
![]() |
![]() |
| 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. |
The benchmark was performed on a Oneplus 6T with Android Q. You can run the benchmark yourself.
*Take this benchmark with a grain of salt. It is very hard to compare databases objectively since they were made for different purposes.
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.
История изменений
2.2.3
Enhancements
2.2.2
Fixes
- Register DateTime adapter on web - #983
2.2.1
Fixes
- Retracted hive@2.2.0 from pub.dev
- Fixed hive web backend null value exception - #968
2.2.0
Enhancements
- Added multiple storage backends for web - #956
2.1.0
Fixes
- Do not return uninitialized box - #916
Enhancements
2.0.6
Fixes
- Fixed issue caused database to crash when executing crash recovery - #914
2.0.5
Enhancements
- Get IndexedDB selectively based on window property - #802
- Added
pathparameter toboxExistsanddeleteBoxFromDiskmethods - #776 - Added
flushmethod to boxes - #852
Fixes
- Don't loose track of box objects if init crashes - #846
2.0.4
Enhancements
- Adds default value support to hive_generator generated class adapters
2.0.3
Fixes
- Fix regression where lists are no longer growable - #631
2.0.2
Fixes
HiveObjectMixinnot assigning box to object - #618
2.0.1
Fixes
BoxEventvalue isnullwhen watching aLazyBox- #592- Allow calling
.init()multiple times, instead of throwing error Hive will print warning to console - Hive will warn developers when registering adapters for
dynamictype
2.0.0
Fixes
- Stable null-safety version
1.6.0-nullsafety.2
Fixes
- Added
defaultValueproperty to@HiveField()annotation - #557
1.6.0-nullsafety.1
Fixes
- Changed
metadependency version to^1.3.0-nullsafetyto support null-safety
1.6.0-nullsafety.0
Breaking changes
- Migrate to null-safety - #521
- Update minimum Dart sdk constraint to 2.12.0-0.
- In order to generate null-safe code use hive_generator >= 0.9.0-nullsafety.0
1.5.0-pre
Enhancements
- Timezone support for DateTime - #419
1.4.4+1
Fixes
- Browser support for
BackendManager.boxExists(boxName, path)- #451
1.4.4
Fixes
- Edge browser support - #357
1.4.3
Enhancements
- Added
Hive.ignoreTypeId(typeId)- #397
Fixes
open(Lazy)Boxcan potentially open a box twice - #345- Remove extra byte reservation in writeBoolLis - #398
1.4.2
Fixes
- Fixed dependency issues and minor improvements
1.4.1+1
Other
- Added docs to all public members
1.4.1
Enhancements
- Minor performance improvements
Fixes
- When a database operation failed, subsequent operations would not be performed
Other
- Fixed GitHub homepage path
1.4.0+1
Enhancements
- Minor performance improvements
Fixes
- Allow more versions of
crypto
1.4.0
Enhancements
- ~1000% encryption / decryption performance improvement
- Added option to implement custom encryption algorithm
- Added
box.valuesBetween(startKey, endKey) - Allow tree shaking to drop encryption engine if no encryption is used
Fixes
Hive.deleteBoxFromDisk()did not work for boxes with upper-case names
More
- Deprecated
encryptionKeyparameter. UseHive.openBox('name', encryptionCipher: HiveAesCipher(yourKey)). - Dropped
pointycastledependency - Dropped
pathdependency
1.3.0
Use latest version of hive_generator
Breaking changes
TypeAdaptersand@HiveType()now require atypeIdHive.registerAdapter()does not need atypeIdanymore.- Removed
BinaryReader.readAsciiString() - Removed
BinaryWriter.writeAsciiString()
Enhancements
- New documentation with tutorials and live code
Fixes
box.clear()resets auto increment counter
More
- Not calling
Hive.init()results in better exception
1.2.0
Breaking changes
- Removed the
Hive.pathgetter - Removed
Hive.openBoxFromBytes()(use thebytesparameter ofHive.openBox()instead) LazyBoxandBoxnow have a common parent class:BoxBase- Lazy boxes need to be opened using
Hive.openLazyBox() - Open lazy boxes can be acquired using
Hive.lazyBox() - Box name bug resolved (more information below)
Enhancements
- Support for relationships,
HiveLists(see docs for details) - Support for inheritance
- Lazy boxes can now have a type argument
LazyBox<YourModel> - Added method to delete boxes without opening them
Hive.deleteBoxFromDisk() - Added
pathparameter to open boxes in a custom path - Improved documentation
Fixes
HiveObjectshave not been initialized correctly in lazy boxes- Fixed bug where uppercase box name resulted in an uppercase filename
- Fixed compaction bug which caused corrupted boxes
- Fixed bug which did not allow the key
0xFFFFFFFF - Fixed bug where not all
BoxEvents have been broadcasted
More
- Changed type of
encryptionKeyfromUint8ListtoList<int>
Important:
Due to a bug in previous Hive versions, boxes whose name contains uppercase characters were stored in a file that also contains upper case characters (e.g. 'myBox' -> 'myBox.hive').
To avoid different behavior on case sensitive file systems, Hive should store files with lower case names. This bug has been resolved in version 1.2.0.
If your box name contains upper case characters, the new version will not find a box stored by an older version. Please rename the hive file manually in that case.
This also applies to the web version.
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 fail 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()fromList<int>toIterable<int>. - Removed the option to register
TypeAdaptersfor a specific box. E.g.box.registerTypeAdapter(). getAt(),putAt(),deleteAt()andkeyAt()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
valuesparameter ofaddAll()fromListtoIterable - Improved documentation
- Preparation for queries
1.0.0
- First stable release
0.5.1+1
- Change
keysparameter ofdeleteAllfromListtoIterable - 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 the browser
- Improved general write performance
- Improved docs
- Added integration tests
0.5.0
- Added
keyComparatorparameter for custom key order - Added
isEmptyandisNotEmptygetters 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 the 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
pathpackage
0.4.0
- Added
BigIntsupport - Added
compactionStrategyparameter - Added automatic crash recovery
- Added
add()andaddAll()for auto-increment keys - Added
getAt(),putAt()anddeleteAt()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
nullis 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
inMemoryoption - Breaking: Minor API changes
- Breaking: Changed Endianness to little
- Breaking: Removed Migrator
0.1.1
- Downgrade to
meta: ^1.1.6to support flutter
0.1.0
- First release


