Hive is a NoSQL database written in Dart and come for all platforms. It also carry remarkable performance benchmark. It is easy to implement and simple to understand.
To use the Hivedb you have to install dependecies and build_runner which can build adapter for model class. The database can be opened using openbox command and all the data can be accessed using the Hive.box(‘data’) . There is also commands for deletion, add and Save etc. There is not querying system available.
For relational data you have to depend on SQLite or other SQL variants.
A Box in Hivedb represent the collection of documents and the database/collection itself.
Dependencies
You need to add the following dependencies to pubspec.yml file.
dependencies: hive: ^1.3.0 hive_flutter: ^0.3.0+1 dev_dependencies: hive_generator: ^0.7.0 build_runner: ^1.7.2
Initializing the DB
The main
is the right place for the initialization and creation of the database , say opening your first Hive Box. Since Hive function asynchronous in nature we need to turn main into async
void main() async { await Hive.initFlutter(); await Hive.openBox<Todo>('todo1'); runApp(MyApp()); }
Model class and Adapters
We can structure our data using Model class, our model class has only one field. Save the file as todo.dart
class Todo { final String item; Todo(this.item); }
To make model work with Hive we need to turn the Todo to a Hive Type.
import 'package:hive/hive.dart'; part 'todo.g.dart'; @HiveType(typeId: 0) class Todo { @HiveField(0) final String item; Todo(this.item); }
and the next step is to create adapters for the class which can be automated by the runner, todo.g.dart mark the file for auto generation.
run the following command on terminal
flutter packages pub run build_runner build --delete-conflicting-outputs
Now you are ready for registering adapter and time for completing the main part
void main() async { await Hive.initFlutter(); Hive.registerAdapter(TodoAdapter()); await Hive.openBox<Todo>('todo'); runApp(MyApp()); }
Adding values
var todobox= Hive.box('todo');
var todo=new Todo('Write next Hive app');
todobox.add(todo);
You can also make use of put method to add data , it is a non async method.
Deleting Values
You can delete document or data using box.deleteAt(index);
Close Boxes and all Boxes
A common error can be occurred while interacting with already opened boxes, it can be fix by override dispose () method as follows
@override void dispose() { Hive.close(); // close all the opend boxes super.dispose(); }
Compacting the Boxes
Hive is append only database, which means that when we change / delete data it do it to the end of file, in effect the more memory can be occupied. To overcome this Hive automatically run compact method, make it save. We can also manually compact our data boxes, even can use some conditional statement.
var box = await Hive.openBox('myBox', compactionStrategy: (entries, deletedEntries) { return deletedEntries > 50; });
The best place to use the method inside our dispose () method ()
@override
void dispose() {
Hive.close(); // close all the opend boxes
Hive.box('todo').compact();
super.dispose();
}
Filtering
May be we miss the filtering mechanism, need not miss it all. Here is sample from documentation
var filteredUsers = userBox.values.where((user) => user.name.startsWith('s'))
ValueListenableBuilder
Finally we need to show the list, which should be aware of changes we made to the Hive boxes. A ValueListenableBuilder can help us. It take the box collection as valueListenable and box as Builder argument. An ideal Builder code will look like
child: ValueListenableBuilder( valueListenable: Hive.box<Todo>('todo1').listenable(), builder: (context, box, child) { return ListView.builder( itemCount: box.length, itemBuilder: (context, index) { return ListTile( title: Text(box.getAt(index).item,style: TextStyle(fontSize: 22,color: Colors.green),), trailing: Icon(Icons.delete), onTap: (){ box.deleteAt(index); }, ); }, ); })
Sample code and Official Documentation
That all you need to know about Hivedb for Flutter, see official documentation . A simple Todo project is available at My repository with full code