TypeAdapters in Hive — Flutter
In this tutorial, we added a feature that allows you to mark your tasks as done. So before you continue with this tutorial, check out the previous one: TODO App Using HIVE
What is TypeAdapter?
Hive supports all primitive types such as List, Map, DateTime and Uint8List. If you want to store other objects, you must register a TypeAdapter that converts the object to and from binary form.
You can either write a TypeAdapter yourself or generate it. In most cases, the generated adapter will work just fine. Sometimes there are little things that you can improve with a manually written adapter.
Generate Adapter
The hive_generator package can automatically generate TypeAdapters for almost any class. To create a TypeAdapter for a class, annotate it with @HiveType and specify a typeId (between 0 and 223). Annotate all fields that should be stored with @HiveField
To generate TypeAdapter for the Task class, you must run the Build task.
flutter packages pub run build_runner build
Register Adapter
However, it is not enough to just create a TypeAdapter. We must also register it, which can be done in two ways.
- Register the TypeAdapter for a single box only.
- Register it for all boxes.
Adding a Task
In the previous tutorial, we created the onAddTask method to store the tasks entered from the TextField into the database. But now we need to create an instance of the Task adapter class and pass that instance to the add() method as a parameter.
Reading Tasks
The easiest way to retrieve data is to call the get() method. Since we are using auto-incrementing keys, we should be able to simply use the index parameter.
Updating a Task
Updating a value is done by overwriting an old value with either the put() or putAt() methods. So let’s create an onUpdateTask() method to mark a task as done.
The End
Congratulations, you have finished this tutorial where you have built a fully functional app that saves your ToDo. Feel free to change the UI to make it better than I did, and add more features.
You can find the complete project on my GitHub:
Do you want to learn more about Hive?
Let us know in the comments below.