Complete Hive Example on Flutter App (with full code)

Marcos Henrique da Silva
4 min readSep 14, 2022

--

Photo by Caspar Camille Rubin on Unsplash

Hive is one of the most interesting resources to store and access local data on Flutter applications. And for me the best feature is the ability to store and recover Dart classes. To do that Hive uses Type Adapters, a method that transform your classes in data that can be stored.

On next I will resume in a few steps how to use the Hive with Type Adaptors but I´m recommend you see all the steps in detail and execute these codes in your computer you by downloading the complete exemple on my GitHub

1. Install packages

The necessary packages to use Hive are:

  • hive
  • hive_flutter
  • hive_generator
  • build_runner

2. Initiate flutter

Once the packages installed you need to initiate Hive on your app, the main() method on main.dart is a good place for that.

3. Create adapter file

As we are working to store entire classes, on the class file, in this case person.dart is necessary indicate the file that will be created by Hive generator. I will talk more about the adapter file on step 5 :)

Important: you will need to do that in all classes files that you want to store!

4. Indicate IDs to classes and atributes

With the indication of adaptor file in the class you need to indicate to Hive generator witch classes and columns will be storage. Is importante to have in mind that each class should be a unique typeId and inside the classes the fields also should be a unique ID

5. Run flutter command

After all classes be prepared run the command below on your terminal

The command flutter packages pub run build_runner build will read all classes in your code and create adapters to translate your classes to binary data and vice versa when you read de stored data. These files will use the name that you indicate on step 3

6. Register adapter

After the execution of the previous step each class with and @HiveType will have and adapter and needed to be register, I’m also recommend the use of main method

7. Opening the box

Now that your application is ready it´s time to understand an importante feature of Hive: the data are stored in boxes and to save and acesses your data you need to open those boxes. To do that I´m use the method bellow to verify if a box is already open and return it or if it needs to be opened.

8. CRUD

After the opening the data box, you can start the CRUD operations, like the images below

You can find the Hive documentation and more detains on Hive Docs website

--

--