Hive Database in Flutter: Store and Retrieve data Locally (2024)

Hive Database in Flutter: Store and Retrieve data Locally (3)

Flutter is a popular mobile application development framework that allows developers to create high-performance applications for both Android and iOS platforms. When it comes to data storage in Flutter, there are several options available such as SQLite, Shared Preferences, and Hive.

Hive is a lightweight and fast NoSQL database that can be used to store data in Flutter applications. In this blog, we will explore how to setup and use Hive database in Flutter.

In this article, we’ll go over these steps to build a simple CRUD app that stores cats data with hive:

  • Setup Hive
  • Type Adapters
  • Storing data
  • Reading data
  • Update and Delete data

So let's get started! OKE?

Hive Database in Flutter: Store and Retrieve data Locally (4)

Before we begin with Setting up Hive, we need to set up our Flutter project, which I already did, and put it in the lib/hive_db_blog folder in my Github repo, it contains the UI and the provider setup. You can clone it from there.

Hive Database in Flutter: Store and Retrieve data Locally (5)

To use Hive in Flutter, we need to add the following dependencies to the pubspec.yaml file:

dependencies:
hive: ^2.2.3
hive_flutter: ^1.1.0

we also need to add hive_generator and build_runner to the dev dependencies:

dev_dependencies:
hive_generator: ^2.0.0
build_runner: ^2.3.3

Next, we need to initialize Hive in the main() function of our Flutter application. We can do this by calling the Hive.initFlutter() method as shown below:

void main() async {
await Hive.initFlutter();
runApp(const MyApp());
}

Hive is a NoSQL database that stores data in key-value pairs. Where value can be of a different type such as int, string, list, or custom objects. To store custom objects in Hive, we need to define type adapters that tell Hive how to serialize and deserialize our objects. We can use the hive_generator package to generate type adapters for our custom objects automatically.

This means we will create a model class and store that entire modal in Hive. My model class is called as cat_model.dart

class CatModel{
final String name;
final String age;
final bool isMale;

const CatModel(this.name, this.age, this.isMale);
}

It's a simple model class. let's make it compatible with Hive by tweaking it a little.

import 'package:hive/hive.dart';
part 'cat_model.g.dart';

@HiveType(typeId: 0)
class CatModel {

@HiveField(0)
final String name;

@HiveField(1)
final String age;

@HiveField(2)
final bool isMale;

const CatModel(this.name, this.age, this.isMale);
}

  • Annotate the model class with @HiveType(), so the generator knows this should be a TypeAdapter.
  • Annotate each field you want to save with @HiveField(index), the index is an int and each index should appear once and you shouldn't change it after registering them.
  • In case you change the field name or its datatype or add a new field — You have to run the type adapter command again and re-run the app to reflect the changes in the app.

We can then generate the type adapters for this class by running the following command in the terminal:

flutter packages pub run build_runner build

This will generate a cat_model.g.dart file that contains the type adapter for our CatModel class.

Finally, register the type adapter in your main function, just add it beneath your hive initialization.

void main() async {
await Hive.initFlutter();
Hive.registerAdapter(CatModelAdapter());
runApp(const MyApp());
}

To store data in Hive, we need to open a Hive box. A box is similar to a table in a traditional SQL database and stores key-value pairs. We can open a box by calling the Hive.openBox() method and passing in the name of the box as a parameter. For example, we can open a box named cats as shown below:

Hive.openBox<CatModel>('cats');

We can open the same box multiple times, returning us the same box instance. However, it is good practice to open it once on app launch and get the box whenever we want to add/update/delete data from it. To get the cat box, we can do the following:

Box<CatModel> catBox = Hive.box<CatModel>('cats');

And there are 2 ways to add data

  • box.add(value) - just gives each value an index and auto increments it.
  • box.put('key', value) - you have to specify the key for each value

Now we can add data to it by creating a new instance of the CatModel class. and add it to Hive database using put() method

For example, we can add a new cat to the box as shown below:

var catModel = CatModel('foo', 4 , true); //creating object
await catBox.put(catModel.name, catModel); //putting object into hive box

In this example, we have added a new cat with a key same as its name foo to the catBox box.

There are different ways to read data from your boxes:

  • box.get('key) - get the value from a key.
  • box.getAt(index) - get the value from an index created with box.add().
  • box.values - this returns an iterable containing all the items in the box.
CatModel? catModel = catBox.get('foo'); //get by key
CatModel? catModel = catBox.getAt(3); //get by index
List<CatModel> catModelList = catBox.values.toList(); //get all items in list

We will use the third method to get all the cats that we have added so far.

To update you can use box.put('key', newValue) to update that value, or box.putAt(index, item) which works like getAt()

for example, let us update the age of our previous cat foo

var catModel = CatModel('foo', 5, true); //creating new object 
await catBox.put(catModel.name, catModel); //putting object into hive box

When we put in a new model with the same key, the old data gets updated.

Deleting items is similar to getting:

  • box.delete('key) - delete by key
  • box.deleteAt(index) - delete by index
  • box.deleteAll(keys) - accepts an iterable of keys, and deletes all the keys given.
Box<CatModel> catBox = await HiveBoxHelperClass.openCatBox();
await catBox.delete('foo'); //delete cat with key (name) as 'foo'

Hurray!, we have successfully completed our ‘C’ ‘R’ ‘U’ ‘D’ in Local database.

Hive Database in Flutter: Store and Retrieve data Locally (6)

Hive is a lightweight and fast NoSQL database that can be used to store data in Flutter applications. In this blog, we have explored how to set up and use Hive in Flutter, including defining Hive type adapters, and storing, reading, updating, and deleting data from Hive. By using Hive in our Flutter applications, we can easily store and retrieve data without the overhead of traditional SQL databases.

Hive Database in Flutter: Store and Retrieve data Locally (2024)

References

Top Articles
13 Recipes for Gastritis - TheDiabetesCouncil.com
Making Pickled Eggs and Beets, Easy Healthy Recipes
Cpmc Mission Bernal Campus & Orthopedic Institute Photos
Walgreens Boots Alliance, Inc. (WBA) Stock Price, News, Quote & History - Yahoo Finance
Bj 사슴이 분수
What Are Romance Scams and How to Avoid Them
Login Page
Kaydengodly
Cad Calls Meriden Ct
Tv Guide Bay Area No Cable
Nm Remote Access
Nj Scratch Off Remaining Prizes
Caliber Collision Burnsville
Wisconsin Women's Volleyball Team Leaked Pictures
Tracking Your Shipments with Maher Terminal
Labor Gigs On Craigslist
Current Time In Maryland
Chic Lash Boutique Highland Village
Daily Voice Tarrytown
Katherine Croan Ewald
Directions To Advance Auto
1v1.LOL - Play Free Online | Spatial
The Grand Canyon main water line has broken dozens of times. Why is it getting a major fix only now?
MLB power rankings: Red-hot Chicago Cubs power into September, NL wild-card race
Chaos Space Marines Codex 9Th Edition Pdf
Employee Health Upmc
8005607994
Piri Leaked
Breckiehill Shower Cucumber
Preggophili
Smartfind Express Login Broward
Roseann Marie Messina · 15800 Detroit Ave, Suite D, Lakewood, OH 44107-3748 · Lay Midwife
Best Laundry Mat Near Me
Craigslist Middletown Ohio
Lawrence Ks Police Scanner
Elanco Rebates.com 2022
The Venus Flytrap: A Complete Care Guide
Tyler Sis 360 Boonville Mo
How Much Is Mink V3
8005607994
Game8 Silver Wolf
Raising Canes Franchise Cost
Trap Candy Strain Leafly
Wayne State Academica Login
Armageddon Time Showtimes Near Cmx Daytona 12
Oppenheimer Showtimes Near B&B Theatres Liberty Cinema 12
Seven Rotten Tomatoes
Tinfoil Unable To Start Software 2022
Www Ventusky
Grace Charis Shagmag
Acellus Grading Scale
Olay Holiday Gift Rebate.com
Latest Posts
Article information

Author: Msgr. Refugio Daniel

Last Updated:

Views: 5501

Rating: 4.3 / 5 (74 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Msgr. Refugio Daniel

Birthday: 1999-09-15

Address: 8416 Beatty Center, Derekfort, VA 72092-0500

Phone: +6838967160603

Job: Mining Executive

Hobby: Woodworking, Knitting, Fishing, Coffee roasting, Kayaking, Horseback riding, Kite flying

Introduction: My name is Msgr. Refugio Daniel, I am a fine, precious, encouraging, calm, glamorous, vivacious, friendly person who loves writing and wants to share my knowledge and understanding with you.