Day 23: Master Hive Database in Flutter — Step-by-Step Guide for Beginners

Hemant Kumar Prajapati
5 min readSep 27, 2024

--

Today, we’re diving into the Hive database — a lightweight, yet powerful NoSQL database perfect for Flutter apps. Hive is fast, secure, and ideal for local storage needs. Whether you’re new to Hive or looking to refine your skills, this guide covers everything you need to know, complete with code examples, common pitfalls, and bonus tips. Let’s get started! 🚀

| What is Hive ? 🐝

Hive is a key-value database written in Dart. It’s well-suited for storing small amounts of data persistently and is a great alternative to SQLite and SharedPrefrences. Here’s why you might love it:

  • 🏎️ Lightning Fast: Hive is known for its speed.
  • 🛠️ Easy to Use: Simple API that integrates smoothly with Flutter.
  • 🔒 Secure: Supports AES-256 encryption out of the box.
  • 🌐 Offline First: Perfect for apps that need to work offline.

| Why Choose Hive ?

Before diving into how to use Hive, let’s compare it to other popular options:

Hive vs SQLite

  • Speed: Hive is generally faster than SQLite for basic read/write operations due to its simpler architecture.
  • Schema: Hive is schema-less, which makes it easier to store different types of data without predefined schemas.
  • Usage: SQLite is more suitable for complex queries and relational data handling.

Hive vs SharedPreferences

  • Data Type Support: Hive supports complex data types and custom objects, whereas SharedPreferences is limited to primitive data types.
  • Performance: Hive is faster and more efficient for larger datasets.
  • Encryption: Hive offers built-in encryption, enhancing security for sensitive data.

| Getting Started with Hive

1. Installing Hive

First things first, add Hive and Hive Flutter packages to your pubspec.yaml file:

dependencies:
hive: ^2.0.5
hive_flutter: ^1.1.0

Then, run:

flutter pub get

2. Initializing Hive

Initialize Hive in your main function before running the app:

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

| Creating a Hive Box 🗃️

A Box in Hive is like a table in a relational database, but much simpler. Let’s create a box to store some data.

1. Open a Box

You need to open a box before you can store data in it:

var box = await Hive.openBox('myBox');

2. Storing Data

Storing data in Hive is super easy:

await box.put('name', 'Hemant Prajapati');

Or store a list of items:

await box.put('friends', ['Alice', 'Bob', 'Charlie']);

Retrieving Data

Retrieving data is just as simple:

var name = box.get('name'); // Hemant Prajapati

Or retrieve a list:

var friends = box.get('friends'); // ['Alice', 'Bob', 'Charlie']

Updating Data

Updating data follows the same pattern as storing it:

await box.put('name', 'Hemant Prajapati');

Deleting Data

Deleting data from a box is straightforward:

await box.delete('name');

| Hive and Custom Objects

What if you need to store custom objects? Hive can handle that too!

1. Define Your Model

Define a model class and annotate it:

import 'package:hive/hive.dart';

part 'person.g.dart';

@HiveType(typeId: 0)
class Person {
@HiveField(0)
String name;

@HiveField(1)
int age;

Person({required this.name, required this.age});
}

2. Generate the Adapter

Run the build runner to generate the type adapter:

flutter packages pub run build_runner build

This command creates a person.g.dart file.

3. Register the Adapter

Register the adapter before opening a box:

void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Hive.initFlutter();

Hive.registerAdapter(PersonAdapter());

var box = await Hive.openBox('myBox');
runApp(MyApp());
}

4. Storing Custom Objects

Now you can store custom objects:

var person = Person(name: 'Hemant Prajapati', age: 30);
await box.put('person', person);

5. Retrieving Custom Objects

Retrieve the stored custom object:

var person = box.get('person') as Person;
print('Name: ${person.name}, Age: ${person.age}');

Advanced Hive Usage

Transactions

  • Hive supports transactions, which allow you to perform multiple operations atomically:
await box.put('name', 'Hemant Prajapati');
await box.put('age', 30);

await box.transaction(() async {
box.put('name', 'Hemant Prajapati');
box.put('age', 28);
});

Watchers

  • You can listen to changes in a Hive box:
box.listenable().addListener(() {
print('Box changed!');
});

| Common Mistakes and How to Avoid Them

⚠️ Forgetting to initialize Hive:

  • Issue: If Hive isn’t initialized, you’ll encounter runtime errors.
  • Solution: Always call Hive.initFlutter() before using Hive.

⚠️ Not registering adapters:

  • Issue: Custom objects need their adapters registered, or you’ll get a type error.
  • Solution: Ensure you call Hive.registerAdapter(YourAdapter()) in the main function.

⚠️ Opening boxes in the wrong place:

  • Issue: Opening boxes in build methods or inside widgets can lead to performance issues and repeated openings.
  • Solution: Open boxes at the start of your app or in an appropriate lifecycle method, ideally in the main function or initState.

⚠️ Incorrect use of keys:

  • Issue: Using keys inconsistently can lead to unexpected behaviors.
  • Solution: Use consistent and meaningful keys for storing and retrieving data.

| Bonus Tips

  • 🌟 Use Hive for settings and preferences: Hive is great for storing app settings, user preferences, and small caches.
  • 🌟 Encryption: Secure sensitive data using Hive’s encryption support.
var encryptedBox = await Hive.openBox('secureBox', 
encryptionCipher: HiveAesCipher(yourEncryptionKey));
  • 🌟 Watch for changes: You can listen to changes in a Hive box.
box.listenable().addListener(() {
print('Box changed!');
});
  • 🌟 Lazy Boxes: Use lazy boxes for large data sets to improve performance by only loading data when accessed.
var lazyBox = await Hive.openLazyBox('myLazyBox');
  • 🌟 Indexing: Hive doesn’t support querying like SQL databases, but you can implement indexing manually by maintaining a map of indexes.
Map<String, int> index = {};
index['Hemant Prajapati'] = 1; // where 1 is the key in the box

| Conclusion 🏁

Hive is an excellent choice for local storage in Flutter apps. It’s fast, easy to use, and perfect for offline functionality. With the steps and tips provided, you should be able to integrate Hive smoothly into your Flutter projects. Happy coding! 💻😊

If you have any questions or run into issues, feel free to drop a comment below. Let’s build something awesome together! 🚀

| 🌟 Enjoyed this tutorial?

For more tips, tutorials, and insights into Flutter, be sure to follow my Medium blog! Stay connected, and let’s continue building amazing things together.

This is just Part 23: Ping me on other platforms… too….

👉 Follow me:

Happy coding! 🎉 !! Happy Flutter !!

💬 Comment Section is Open!

Share your thoughts or ask questions below.

👏 Applaud if you enjoyed this!

Your claps help others find this content.

➕ Follow for more!

Stay updated with more tips and tutorials.

🌿 Thank you for reading! If you liked this post and want to support me, you can buy me a coffee here 👇

--

--

Hemant Kumar Prajapati

Flutter developer 🎩✨ crafting cross-platform apps. Sharing fun coding tips! If you enjoy my guides, Checkout my hopp bio! https://www.hopp.bio/hemant-prajapati