flutter hive
hive is a lightweight and blazing fast key-value database written in pure dart. inspired by bitcask.
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 (key-value)
- 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 entries
sharedpreferences is on par with hive when it comes to read performance. sqlite performs much worse.
write 1000 entries
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]
.
dependencies:
hive: ^[version]
hive_flutter: ^[version]
dev_dependencies:
hive_generator: ^[version]
build_runner: ^[version]
usage
import 'package:hive/hive.dart';
void main() async {
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
Comments are closed.